[英]SQL query NOT IN from 3 tables with conditions
I have tables scructure: 我有表结构:
old_data OLD_DATA
| | email | 电邮| type | 类型
/////////////////////////////// ///////////////////////////////
clients 客户
| | email1 | email1 |
////////////////////////////// //////////////////////////////
trashes 象垃圾一样清除
| | email | 电邮|
I need to find records that are not in table clients
, but still exists in table old_data
where it have type = 'Accounts'. 我需要查找不在表clients
中但仍存在于表old_data
中的记录,该记录的类型为'Accounts'。 So I wrote this code: 所以我写了这段代码:
SELECT `email` FROM `old_data`
WHERE `type` = 'Accounts' AND `email` NOT IN (SELECT `email1` FROM `clients`))
Then I need to find in this result records, that are not in table trashes
. 然后,我需要在此结果记录中找到不在表trashes
。 So I wrote this code: 所以我写了这段代码:
SELECT * FROM (SELECT `email` FROM `old_data`
WHERE `type` = 'Accounts' AND `email` NOT IN (SELECT `email1` FROM `clients`)) AS t1
WHERE t1.email NOT IN (SELECT `email` FROM `trashes`)
The problem here is, I have multiple records in table old_data
for 1 email and type 'Accounts'. 这里的问题是,我在表old_data
中有1条电子邮件的多个记录,然后键入“帐户”。 Same is in table trashes
, but not in table clients
. 在表trashes
,但在表clients
不是。 I need to write query like: 我需要这样写查询:
Get all records from old_data
where is not clients
email, but if clients
email1 matches old_data
email, remove all records with that emails from result. 从不是clients
电子邮件的old_data
中获取所有记录,但是如果clients
email1与old_data
电子邮件匹配,则从结果中删除带有该电子邮件的所有记录。 But then if from this result matches email with email from table trashes
, remove from result only one record with that email. 但是,如果从此结果中将电子邮件与表trashes
中的电子邮件匹配,则从结果中仅删除该电子邮件中的一条记录。
Please help, I'm lost... 请帮助,我迷路了...
You can use not in
by chaining the conditions. 您可以通过链接条件使用not in
。
SELECT od.`email`
FROM `old_data` od
WHERE od.`type` = 'Accounts' AND
od.`email` NOT IN (SELECT `email1` FROM `clients`) AND
od.email NOT IN (SELECT `email` FROM `trashes`);
I prefer not exists
with a subquery because it handles NULL
values better. 我更喜欢子查询not exists
,因为它可以更好地处理NULL
值。
I managed to work it with another parameter. 我设法使用另一个参数。
SELECT * FROM (SELECT `email`, `secretId` FROM `old_data`
WHERE `type` = 'Accounts' AND `email` NOT IN (SELECT `email1` FROM `clients`)) AS t1
WHERE t1.secretId NOT IN (SELECT `secretId` FROM `trashes` WHERE `type` = 'Accounts')
Also works with 也适用于
SELECT od.`email`, od.`secretId`
FROM `old_data` od
WHERE od.`type` = 'Accounts' AND
od.`email` NOT IN (SELECT `email1` FROM `clients`) AND
od.`secretId` NOT IN (SELECT `secretId` FROM `trashes` WHERE `type` = 'Accounts');
Thanks for helping. 感谢您的帮助。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.