问题
We wrote a cleanup script in SQL(DB2) as400 to do cleanup of tables. ps we are fixing the processes that is causing the data issues.
The SQL : DELETE FROM p6prodpf A WHERE (0 = (SELECT COUNT(*) FROM P6OPIPF B WHERE B.OPIID = A.OPIID))
Its simple code to check if theres a record in p6prodpf
that has no record in P6OPIPF
then delete the record in p6prodpf
.
My problem that I am facing is that there's instances where the p6prodpf
is being deleted even if theres a record in P6OPIPF
.
Is there a better way of doing this or safer way.. Is there any reason why this could be happening.
The script runs 3am in the morning.
It also feels like a sequencing issue but when I check the record in P6OPIPF
it exists but its deleted in p6prodpf
.
回答1:
Use "NOT EXISTS" instead of "0 =":
DELETE FROM p6prodpf A WHERE NOT EXISTS (SELECT 1 FROM P6OPIPF B WHERE B.OPIID = A.OPIID)
来源:https://stackoverflow.com/questions/31676517/sql-cleanup-script-delete-from-one-table-thats-not-in-the-other