我需要清理一个数据库中的记录,如果它们不存在于其他数据库中。
很难解释,下面是一个例子:
Table Users
-----------
id
username
password
Table Articles
--------------
id
title
created_by
edited_by
created_by
和deleted_by
包含用户ID。我有3-4个表,其结构与articles表几乎相同,我想从没有任何记录的表用户(如tables)中删除用户。
我的意思是在
created_by
和edited_by
表中的任何一篇文章中都找不到ID的用户。怎么做?
我首先想看看是否可以根据用户选择所有表的所有数据,但是服务器无法执行查询:
SELECT * FROM `users`
JOIN `articles`
ON `articles`.`created_by` = `users`.`id`
AND `articles`.`edited_by` = `users`.`id`
JOIN `articles_two`
ON `articles_two`.`created_by` = `users`.`id`
AND `articles_two`.`edited_by` = `users`.`id`
JOIN `articles_three`
ON `articles_three`.`created_by` = `users`.`id`
AND `articles_three`.`edited_by` = `users`.`id`
JOIN `articles_four`
ON `articles_four`.`created_by` = `users`.`id`
AND `articles_four`.`edited_by` = `users`.`id`
JOIN `articles_five`
ON `articles_five`.`created_by` = `users`.`id`
AND `articles_five`.`edited_by` = `users`.`id`
JOIN `articles_six`
ON `articles_six`.`created_by` = `users`.`id`
AND `articles_six`.`edited_by` = `users`.`id`;
最佳答案
我认为最干净的方法是not in
子句中的select
:
select *
from users u
where u.id not in (select created_by from articles where created_by is not null) and
u.id not in (select edited_by from articles where edited_by is not null) and
u.id not in (select created_by from articles_two where created_by is not null) and
u.id not in (select edited_by from articles_two where edited_by is not null) and
u.id not in (select created_by from articles_three where created_by is not null) and
u.id not in (select edited_by from articles_three where edited_by is not null) and
u.id not in (select created_by from articles_four where created_by is not null) and
u.id not in (select edited_by from articles_four where edited_by is not null)
应该通过在不同的
created_by
和edited_by
列上设置索引来提高性能。