I know two ways to paste without duplication. The first uses a sentence WHERE NOT EXISTS:
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)
another performs 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 that one is faster than the other, or does it depend on tables? Is there any other way that is better than both?
source
share