插入记录如果在sql中不存在,则重复列名

时间:2010-07-27 17:46:19

标签: mysql sql activerecord insert mysql-error-1060

我想要一个解决方案来插入记录,如果它不存在所以我在这里搜索并找到了解决方案,但我有另一个问题

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个数字相同时出现问题

2 个答案:

答案 0 :(得分:15)

使SQL工作的最小变化是在select语句中添加别名:

INSERT 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)

答案 1 :(得分:4)

INSERT INTO closed_answers (question_id, subject_id) 
SELECT * FROM (SELECT 2 a, 2 b) AS tmp 
WHERE NOT EXISTS ( 
    SELECT 1 FROM closed_answers WHERE question_id = 2 AND subject_id = 2 
) LIMIT 1 

带子查询的select语句很奇怪,但是问题在于你没有命名所选的列。当使用存在时,仅选择1而不是字段就足够了。此外,限制1也没有必要。