如果条件成立,则插入MySQL

4

我有一个猫ID - 帖子ID关系表。

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

我使用 SELECT WHERE cat_id = 11 AND post_id = 32,如果没有结果,我会执行 INSERT。是否可以将这两个查询合并为一个?
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
                     );

抱歉,rt是什么意思?我的表名是cats_rel,你的查询语句没有起作用。 - Positivity
1
rt 是一个表别名。实际上,在这个查询中并不需要它。 - Gordon Linoff
我收到了这个错误:#1064 - 您的SQL语法有误;请检查与您的MySQL服务器版本相对应的手册,以获取正确的语法,位于第3行的位置是“where not exists (select 1 from cats_rel where cat_id = 11 and message_id = 32)” - Positivity
我不知道toinsert和cr是什么意思,也不知道“它们只出现在查询中一次”是什么意思,但是... Gordon Linoff做得很好! - Positivity
1
toinsertcr是表别名。这些值仅在子查询中出现一次。在其他地方,它们通过列名进行引用。 - Gordon Linoff

3
您可以使用“替换”来:
REPLACE INTO 'yourtable'
SET `cat_id` = 11, `post_id` = 32;

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

更新: 为了让它工作,您应该向这一对列添加一个唯一键,而不仅仅是一个。

ALTER TABLE yourtable ADD UNIQUE INDEX cat_post_unique (cat_id, post_id); 

你的查询只是插入和插入。我运行了5次,现在有5个11和32! - Positivity
ALTER TABLE yourtable ADD UNIQUE(cat_id, post_id); 将此代码翻译为中文:在你的表中添加唯一约束(cat_id, post_id)。 - mbouzahir
添加唯一的和任何执行都会破坏之前的记录。我需要将许多帖子链接到一个类别。这样,只有一个帖子可以链接到一个类别! - Positivity
你应该对这一列添加唯一性,而不是仅仅添加一个。ALTER TABLE yourtable ADD UNIQUE INDEX cat_post_unique (cat_id, post_id); - mbouzahir
1
你好,请编辑你的答案并注意最后一条评论,这样我就可以将其标记为已接受,因为它比当前已接受的答案更简单。谢谢。 - Positivity

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接