我想要一个解决方案来插入一个记录,如果它不存在所以我在这里搜索并找到了解决方案,但我有另一个问题
INSERT INTO closed_answers (question_id,subject_id)
SELECT * FROM (SELECT 2,2) AS tmp
WHERE NOT EXISTS (
SELECT question_id FROM closed_answers WHERE question_id = 2 AND subject_id = 2
) LIMIT 1
输出是
#1060 - Duplicate column name '2'
如果我使用任何不相同的2个数字它将起作用,但当2个数字相同时出现问题
最佳答案
使sql工作的最小变化是为select语句添加别名:
原文链接:/mysql/434208.htmlINSERT INTO closed_answers (question_id,subject_id)
SELECT * FROM (SELECT 2 AS question_id,2 AS subject_id) AS tmp
WHERE NOT EXISTS (
SELECT question_id
FROM closed_answers
WHERE question_id = 2 AND subject_id = 2
) LIMIT 1
但是,如果您对(question_id,subject_id)有唯一约束,则可以使用INSERT IGNORE:
INSERT IGNORE INTO closed_answers (question_id,subject_id)
VALUES (2,2)