I am having a difficult time forming a conditional INSERT
I have x_table with columns (instance, user, item) where instance ID is unique. I want to insert a new row only if the user already does not have a given item.
For example trying to insert instance=919191 user=123 item=456
Insert into x_table (instance, user, item) values (919191, 123, 456)
ONLY IF there are no rows where user=123 and item=456
Any help or guidance in the right direction would be much appreciated.
The syntax may vary depending on your DB...
With a
UNIQUE(user, item)
, do:the
user=123
bit is a "no-op" to match the syntax of theON DUPLICATE
clause without actually doing anything when there are duplicates.You can also use
INSERT IGNORE
which silently ignores the insert instead of updating or inserting a row when you have a unique index on (user, item).The query will look like this:
You can add the unique index with
CREATE UNIQUE INDEX user_item ON x_table (user, item)
.Slight modification to Alex's response, you could also just reference the existing column value:
You can use the following solution to solve your problem:
Have you ever tried something like that?