I know of two ways to insert without duplication. The first is using a WHERE NOT EXISTS
clause:
INSERT INTO table_name (col1, col2, col3)
SELECT %s, %s, %s
WHERE NOT EXISTS (
SELECT * FROM table_name AS T
WHERE T.col1 = %s
AND T.col2 = %s)
the other is doing a LEFT JOIN
:
INSERT INTO table_name (col1, col2, col3)
SELECT %s, %s, %s
FROM ( SELECT %s, %s, %s ) A
LEFT JOIN table_name B
ON B.COL1 = %s
AND B.COL2 = %s
WHERE B.id IS NULL
LIMIT 1
Is there a general rule as to one being faster than the other, or does it depend on the tables? Is there a different way which is better than both?