I have a master table as:
id(PRIMARY KEY) customername zipcode identitynumber createdtimestamp
ABC JOHN 91421 12346 2:09:31 AM
DEF CARTER 91421 12346 2:09:31 AM
PQR AURTHUR 13133 767676 2:09:31 AM
and another table child as below.
ID(PRIMARY) customername zipcode identitynumber
xyz peter 91421 12346
MNO CARTER 91421 12346
I want to get all the records from master table that are having createdtimestamp is less than 24 hours and insert in to child table only if zipcode, identitynumber match but not customername. Basically inserting various names in child table having same zipcode and identitynumber and primary key of master table. So, finally child table should has:
ID(PRIMARY) customername zipcode identitynumber
xyz peter 91421 12346
MNO CARTER 91421 12346
ABC JOHN 91421 12346
I tried with below query but failing as primary key violation even though child tables doesn't have primary key.
insert into childtable
(ID,customername,zipcode,identitynumber)
select
master.id ,
master.customername,
child.zipcode,
child.identitynumber
FROM childtable child
inner JOIN mastertable master ON master.CREATED_TIMESTAMP > DATE_SUB(NOW(), INTERVAL 24 HOUR)
and master.identitynumber = child.identitynumber
AND master.zipcode = child.zipcode
WHERE NOT EXISTS
( SELECT 1 FROM childtable existingchild
WHERE existingchild.identitynumber = master.identitynumber
AND existingchild.customername = master.customername
AND existingchild.zipcode = master.zipcode);
Please advise with best query.