我试图仅在没有包含两个值的现有记录时才将记录插入表中。此查询抛出错误: "语法在' WHERE NOT EXISTS"
附近使用我已尝试过SO帖子中的各种示例,但似乎无法实现这一目标。
INSERT INTO tasks_admin2agent
(trans_id,category,task_name,task_detail,date_due_d)
VALUES
('2186597-L1','Listing','Incomplete Listing Record', 'Please complete the
listing record','2018-03-31')
WHERE NOT EXISTS
(SELECT
trans_id,task_name
FROM tasks_admin2agent
WHERE trans_id = '2186597-L1'
AND task_name = 'Incomplete Listing Record'
)
答案 0 :(得分:1)
对我而言,如果你改变" VALUES"到" SELECT"。但我无法解释为什么会这样做
INSERT INTO tasks_admin2agent
(trans_id,category,task_name,task_detail,date_due_d)
SELECT
('2186597-L1','Listing','Incomplete Listing Record', 'Please complete the
listing record','2018-03-31') FROM tasks_admin2agent
WHERE NOT EXISTS
(SELECT
trans_id,task_name
FROM tasks_admin2agent
WHERE trans_id = '2186597-L1'
AND task_name = 'Incomplete Listing Record'
)
答案 1 :(得分:1)
试试这个:
INSERT INTO tasks_admin2agent
(trans_id,category,task_name,task_detail,date_due_d)
SELECT
'2186597-L1','Listing','Incomplete Listing Record', 'Please complete the
listing record','2018-03-31' from tasks_admin2agent
WHERE NOT EXISTS
(SELECT
*
FROM tasks_admin2agent
WHERE trans_id = '2186597-L1'
AND task_name = 'Incomplete Listing Record'
);
您还可以查看: INSERT VALUES WHERE NOT EXISTS
答案 2 :(得分:1)
尝试类似
的内容INSERT INTO tasks_admin2agent
(trans_id,category,task_name,task_detail,date_due_d)
SELECT
'2186597-L1','Listing','Incomplete Listing Record', 'Please complete the
listing record','2018-03-31' FROM tasks_admin2agent
WHERE NOT EXISTS
(SELECT
*
FROM tasks_admin2agent
WHERE trans_id = '2186597-L1'
AND task_name = 'Incomplete Listing Record'
);
您可以尝试Demo
答案 3 :(得分:1)
只需在相关的两列上设置(Composite-)Key-Constraint(唯一):
ALTER TABLE tbl ADD UNIQUE KEY `uniqueConstraint` (col1, col2);
使用常规插入物和"手柄" "重复关键错误" - >这意味着价值对已经存在。
这也允许您将查询与ON DUPLICATE KEY UPDATE
- 语法结合使用。 (如果需要)
请注意,中止的插入或On duplicate key update
无论如何都会消耗下一个自动增量ID。
答案 4 :(得分:0)