Let's consider that I have a Table A that I use to generate a Table B. I have no primary key or unique key I could use for a ON DUPLICATE KEY
.
My Table B has 3 columns: A, B, and C.
I want to INSERT
this only if the row already doesn't exist. I can determine if the row exist be the combination of A and B. I use a WHERE NOT EXISTS
statement to do so.
INSERT INTO TableB
(A, B, C)
SELECT
SUM(A),
SUM(B),
SUM(C)
FROM TableA
WHERE NOT EXISTS (SELECT * FROM TABLE B WHERE A=A AND B=B)
GROUP BY A, B
If Table B is empty, the row are inserted. However, as soon as Table B has a record, no rows are inserted even if they doesn't already exist in Table B.