MySQL插入条件

时间:2013-08-24 18:43:48

标签: mysql sql

我有这个猫id - post id relation table。

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

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

3 个答案:

答案 0 :(得分: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
                     );

答案 1 :(得分:3)

您可以使用替换

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

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

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

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

答案 2 :(得分: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);
相关问题