mySQL 仅在不存在但有更多条件时插入

mySQL insert only when not exists but with more conditions

我有 table product_pushjobs with 5 列:id、用户、产品、连接、完成` ID 是主要的且自动递增。

insert,我只填userproduct(有时connection,视情况而定)

我想在有 userproduct 的另一行时阻止插入,但 仅当 done IS NULL 时。 所以 table 可以有一百万行相同的用户和产品,但当有一个 done is NULL .

我在这个网站上发现了很多不同的建议,但与我的不完全相同。 我已经试过了,但出现错误:

INSERT INTO product_pushjobs (user, product) 
VALUES (5,9936) 
WHERE NOT EXISTS (
    SELECT id FROM product_pushjobs 
    WHERE user=5 AND product=9936 AND connection IS NULL AND done IS NULL
)

mysql 错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT * FROM product_pushjobs WHERE user=5 AND product=9936 A' at line 1

我猜这将是一个愚蠢的问题,但我需要快速解决这个问题。

INSERT 语句不可能添加 WHERE-clause。

因此,您可以:

INSERT INTO product_pushjobs (user, product) 
    SELECT 5,9936 WHERE (SELECT 1 
                           FROM product_pushjobs 
                           WHERE user=5 
                             AND product=9936 
                             AND connection IS NULL 
                             AND done IS NULL) IS NULL

查询 SELECT 5,9936.... 的结果用于输入到 INSERT 语句,但没有结果。如果 record-to-insert 不存在,WHERE-clause 确保只返回一条记录。

SELECT 1 也可以是 SELECT id,但由于 id 没有做任何事情,我选择把 1 放在那个地方。