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

前端之家收集整理的这篇文章主要介绍了mysql – 如果sql中不存在,则插入记录,重复列名前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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语句添加别名:

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)
原文链接:/mysql/434208.html

猜你在找的MySQL相关文章