Is it possible to insert a new row if a condition is meet?
For example, i have this table with no primary key nor uniqueness
+----------+--------+
| image_id | tag_id |
+----------+--------+
| 39 | 8 |
| 8 | 39 |
| 5 | 11 |
+----------+--------+
I would like to insert a row if a combination of image_id and tag_id doesn’t exists
for example;
INSERT ..... WHERE image_id!=39 AND tag_id!=8
I think you’re saying: you need to avoid duplicate rows in this table.
There are many ways of handling this. One of the simplest:
As @Henrik Opel pointed out, you can use a check constraint on the combined columns, but then you have to have a try/catch block somewhere else, which adds irrelevant complexity.
Edit to explain that comment…
I’m assuming this is a table mapping a many-to-many relationship between Movies and Tags. I realize you’re probably using php, but I hope the C# pseudocode below is clear enough anyway.
If I have a
Movieclass, the most natural way to add a tag is anAddTag()method:There’s no practical way to check for duplicates earlier in the process, because another user might Tag the Movie at any moment, so there’s no way around this.
Note: If trying to insert a dupe record means there’s a bug, then throwing an error is appropriate, but if not, you don’t want extra complexity in your error handler.