Removing all records from a table that don't exist in another table
I've got a table with a lot (>20.000) records. It's time to clean those up a little 开发者_JAVA百科because queries are beginnen to take up a lot of recourses. I have another (temporary) table with a recent records. All records in the first table that don't exist in the second one can go. However, I need to keep the id's for the recent records because of some joins, so I can't just TRUNCATE and then copy the table. Is there any way yo do this?
DELETE FROM old_table WHERE id NOT IN (SELECT id FROM temp_table)
Edit:
id NOT IN (SELECT id FROM temp_table)
is a lousy construction. If you have large tables and your server settings are tuned to low memory, you will execute this forever.
@Piskvor's answer is a longer, but a much better query, that will work best on low-memory setups. And when I say "low memory", I mean database servers that do not take up a full high-end computer, so pretty much any system that manages a small business website or stuff like that.
This will give you the id
s of rows that don't have a corresponding row (matched by recordid
column - yours may be different) in the other table:
SELECT t1.id
FROM firsttable t1
LEFT JOIN secondtable t2
WHERE t1.recordid = t2.recordid
AND t2.id IS NULL
That allows you to check that you're actually selecting the correct rows to delete. Then, plug it into a DELETE:
DELETE FROM firsttable WHERE firsttable.id IN (
SELECT t1.id
FROM firsttable t1
LEFT JOIN secondtable t2
WHERE t1.recordid = t2.recordid
AND t2.id IS NULL
)
精彩评论