我有这个 cat id - post id 关系表。
+----+--------+---------+
| id | cat_id | post_id |
| | | |
| 1 | 11 | 32 |
| 2 | ... | ... |
+----+--------+---------+
我使用 SELECT WHERE cat_id = 11 AND post_id = 32
然后如果没有找到结果,我会 INSERT
。
我可以将这两个查询重写为一个吗?
最佳答案
你可以这样做:
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);
编辑:
糟糕。以上在 MySQL 中不起作用,因为它缺少 from
子句(尽管在许多其他数据库中有效)。无论如何,我通常将这些值放在子查询中,这样它们只在查询中出现一次:
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
);
关于MySQL 插入条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18421905/