Reputation: 12753
I have a 'users' SQL table structure like this (the ID is randomly generated, not auto-incremented):
ID name deleted lastActive
3242 Joe 0 20-6-2012 23:14
2234 Dave 0 20-6-2012 23:13
2342 Simon 1 20-6-2012 23:02
9432 Joe 1 20-6-2012 22:58
There can be multiple deleted (deleted=1) users with the same name, but only 1 undeleted user with the same name (so adding Simon is fine, but Dave is not). How can I insert only if there is not a record already with the same name and deleted=0, in one SQL query? I need something like this:
INSERT INTO users (ID, name) VALUES ($id, $name)
WHERE NOT EXISTS (SELECT 1 FROM users WHERE name = $name AND deleted = 0)
But this is not correct syntax.
Upvotes: 4
Views: 480
Reputation: 44373
Setup a LEFT JOIN with
This is the query
INSERT INTO users (ID,name)
SELECT A.* FROM
(SELECT RAND() ID,'$name' name) A LEFT JOIN
(SELECT name FROM users WHERE name='$name' AND deleted=0) B
USING (name) WHERE B.name IS NULL;
Upvotes: 3
Reputation: 128
INSERT INTO users SELECT '1', 'Bob','','' FROM DUAL WHERE NOT EXISTS(SELECT ID FROM users WHERE name = 'Bob' AND deleted ='0' LIMIT 1)
Upvotes: 0
Reputation: 6611
Make sure that ID Is either a primary or unique key and create a index on all three ID, name and deleted columns.
REPLACE INTO users (ID, name) VALUES ($id, $name)
Upvotes: 1
Reputation: 12244
INSERT INTO users (ID, name)
SELECT $id, $name WHERE NOT EXISTS (
SELECT 1 FROM users WHERE name = $name AND deleted = 0
)
Upvotes: 0