MySQL 插入条件

标签 mysql sql

我有这个 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/

相关文章:

sql - 在 SQL 中选择到表中。它们是如何储存的?

bash - Mysql LOAD LOCAL DATA INFILE - 中文字符问题

mysql - 简单 Rails SQL 错误

sql - 如何在 SQLite 中逻辑删除记录

sql - 数据库设计受UI需求影响: Should I make an extra field or a new relation?

mysql - SQL BETWEEN 字符串,其中第二个是最小的

c# - sql查询统计每小时的数据输入

mysql - MySQL更新查询奇怪的行为

Mysql如何根据时间检索数据?

php - 如何在 Fullcalendar 中保存事件?