[英]Efficiently deleting rows from one table where not matching another [MySQL]
So, I have two tables, users and points.所以,我有两个表,用户和点。 A lot of users no longer have points (literally and by table) -- so I wish to delete them.很多用户不再有积分(字面意思和表格)——所以我希望删除它们。 I try and achieve this by doing this, but it basically times out (about one hundred thousand rows in both tables).我尝试通过这样做来实现这一点,但它基本上会超时(两个表中大约有十万行)。 I'm doing select rather than delete because I want to verify the data before issuing the same query as a delete:我正在做 select 而不是删除,因为我想在发出与删除相同的查询之前验证数据:
SELECT WWW t1
FROM users t1
JOIN points t2 ON t1.id != t2.user_id;
Both tables have an ID that matches each other.两个表都有一个相互匹配的 ID。 If a user has a point, there will be a matching ID.如果用户有一个点,就会有一个匹配的 ID。 If there is no longer a point for that user, there is no matching ID.如果该用户不再有积分,则没有匹配的 ID。 Therefor, .= therorhetically should delete all the no longer needed users.因此,.=理论上应该删除所有不再需要的用户。
How can I do this without timing out my database?如何在不使数据库超时的情况下做到这一点?
I would recommend not exists
:我建议not exists
:
delete from users
where not exists (select 1 from points p where p.user_id = users.id)
This should be an efficient option, if you have the right index in place, that is: points(user_id)
.如果您有正确的索引,这应该是一个有效的选择,即: points(user_id)
。
On the other hand, if you are deleting a great proportion of the table, it might be simpler to move that rows that you want to keep to a temporary table, then truncate and recreate the table:另一方面,如果您要删除表的很大一部分,将要保留的行移动到临时表中,然后截断并重新创建表可能会更简单:
create table tmp_users as
select u.*
from users
where exists(select 1 from points p where p.user_id = u.id)
truncate table users; -- back it up first!
insert into users select * from tmp_users;
drop table tmp_users;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.