I have an array:
[1, 2, 3, 5]
And I have a table:
+--------+
| number |
+--------+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
+--------+
What I want to do is compare the two and delete the difference from the table. So in this case, 4.
What is the best way to do this? (I'm using MySQL(i) and php)
The following methods will work, but they have downsides:
Iterating through the array and manually adding each item to the
IN
part of theWHERE
clause:DELETE FROM tbl WHERE number NOT IN (1, 2, 3, 5)
Issue is this is a potential risk with unsafe strings and sql queries have size limits.
Creating a temporary table with the array and using that to make the comparison:
DELETE FROM tbl WHERE number NOT IN (SELECT num FROM tmp)
This is very resource intensive (creating and dropping a new table for each connection) and slow.