4

我有这个猫 id - 发布 id 关系表。

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

我使用SELECT WHERE cat_id = 11 AND post_id = 32,然后如果没有找到结果,我会使用INSERT. 我可以在一个中重写这两个查询吗?

4

3 回答 3

4

你可以这样做:

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
                     );
于 2013-08-24T18:45:11.607 回答
3

您可以使用替换

REPLACE INTO 'yourtable'
SET `cat_id` = 11, `post_id` = 32;

如果记录存在,它将覆盖它,否则将被创建;

更新:为此,您应该为这对列添加一个唯一键,而不仅仅是一个

ALTER TABLE yourtable ADD UNIQUE INDEX cat_post_unique (cat_id, post_id); 
于 2013-08-24T18:51:04.897 回答
0

我们可以对 MySQL 使用“from dual”子句:

insert into cats_rel(cat_id, post_id)
select 11, 32 from dual
where not exists (select 1 from cats_rel where cat_id = 11 and post_id = 32);
于 2017-01-08T12:10:31.263 回答