insert - where not exists
I would l开发者_开发知识库ike to insert a record into a table if a record doesnt exist already exist with that domain name. The following SQL should achieve this but is getting an error.
The reason I want to do the update first is because I am doing multiple updates later in my code and need the record in my table first before doing all of the updates.
Why am I getting an error on this mySQL query?
insert into domain (name)
values ('domain.com.au')
WHERE NOT EXISTS
(
select name
from domain
where name = 'domain.com.au'
);
Both queries when split work fine but when together do not.
Let your database handle it for you. Use a unique index on name
and your INSERT will fail if you try to insert a duplicate.
CREATE UNIQUE INDEX idx_name ON domain (name)
You cannot combine WHERE
with INSERT
clause. Use REPLACE INTO
instead.
What error are you getting?
My guess would be the that the select inside the 'where not exists' is not allowed.
精彩评论