Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert record if not exists in sql, duplicate column name

i wanted a solution to insert a record if it isn't there so i searched here and found a solution but i have another problem

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

the output is

#1060 - Duplicate column name '2'

if i used any 2 numbers that aren't identical it will work but the problem arise when the 2 numbers are the same

like image 871
Nadeem Khedr Avatar asked Jul 27 '10 17:07

Nadeem Khedr


People also ask

How do I insert without duplicates in SQL?

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

Are duplicate column names allowed in the CTE?

Duplicate names within a single CTE definition aren't allowed. The number of column names specified must match the number of columns in the result set of the CTE_query_definition.


1 Answers

The smallest change to make your SQL work is to add aliases to your select statement:

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

However if you have a unique constraint on (question_id, subject_id) then you can use INSERT IGNORE instead:

INSERT IGNORE INTO closed_answers (question_id, subject_id)
VALUES (2, 2)
like image 199
Mark Byers Avatar answered Sep 30 '22 11:09

Mark Byers