gpt4 book ai didi

MySQL从不在的数据库中选择

转载 作者:行者123 更新时间:2023-11-29 00:30:52 26 4
gpt4 key购买 nike

如果记录在另一个数据库中不存在,我需要从一个数据库中清除记录。
解释起来相当困难,所以这里有一个例子:

Table Users
-----------
id
username
password

Table Articles
--------------
id
title
created_by
edited_by

created_bydeleted_by 包含用户 ID。我有 3-4 个表,其结构与文章表几乎相同,我想从表用户中删除在类似文章的表中没有任何记录的用户。
我的意思是在 created_byedited_by 表中的任何类似文章的表中都找不到 ID 的用户。
怎么做?
我先试了下,看能不能按用户select所有表的所有数据,但是服务器无法执行查询:

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 inselect 子句中:

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_byedited_by 列上建立索引应该有助于提高性能。

关于MySQL从不在的数据库中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16610975/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com