Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Insert if Condition

Tags:

sql

mysql

I Have this cat id - post id relation table.

+----+--------+---------+
| id | cat_id | post_id |
|    |        |         |
| 1  |   11   |   32    |
| 2  |   ...  |   ...   |
+----+--------+---------+

I use SELECT WHERE cat_id = 11 AND post_id = 32 and then if no result found, I do INSERT. Can I rewrite these two queries in One?

like image 562
Positivity Avatar asked Mar 23 '23 16:03

Positivity


1 Answers

You can do something like this:

insert into cats_rel(cat_id, post_id)
    select 11, 32
    where not exists (select 1 from cats_rel where cat_id = 11 and post_id = 32);

EDIT:

Oops. That above doesn't work in MySQL because it is missing a from clause (works in many other databases, though). In any case, I usually write this putting the values in a subquery, so they only appear in the query once:

insert into cats_rel(cat_id, post_id)
    select toinsert.cat_id, toinsert.post_id
    from (select 11 as cat_id, 32 as post_id) toinsert
    where not exists (select 1
                      from cats_rel cr
                      where cr.cat_id = toinsert.cat_id and cr.post_id = toinsert.post_id
                     );
like image 200
Gordon Linoff Avatar answered Apr 06 '23 06:04

Gordon Linoff