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?
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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With