[英]SQL statement for join but not in other table
I have two tables: customer
and mailing
: 我有两个表:
customer
和mailing
:
+==========+ +=============+
| customer | | mailing |
+==========+ +=============+
| id | | id |
+----------+ +-------------+
| name | | customer_id |
+----------+ +-------------+
| mailing_id |
+-------------+
Every time I send a mailing to a customer, I add a row in the mailings table with that mailing id. 每次向客户发送邮件时,我都会在邮件表中添加带有该邮件ID的行。 One mailing can be sent to multiple customers.
一封邮件可以发送给多个客户。
I want to have a sql call that returns all customers that have not yet received a certain mailing. 我希望有一个sql调用,该调用返回尚未收到特定邮件的所有客户。 How to ?
如何 ?
I am using mysql 我正在使用mysql
select * from customer where id not in (
select customer_id from mailing where mailing_id = @mailing_id
)
SELECT * FROM customers c
JOIN mailings m
ON c.id = m.id
WHERE NOT EXISTS (
SELECT id
FROM mailings i
WHERE i.id = c.id
GROUP BY i.id
)
Something like 就像是
Select c.ID, c.Name
From Customers C
left Join mailing m On c.id = m.customer_id
where m.customer_id is null
What you describe is called an ANTI JOIN
. 您所描述的称为
ANTI JOIN
。 Usually there are three different ways for formulating it in SQL: A NOT IN
condition with a subquery, a NOT EXISTS
condition with a correlated subquery, or a LEFT JOIN
with a NOT NULL
condition. 通常,在SQL中用三种不同的方式来表达它:带有子查询的
NOT IN
条件,带有相关子查询的NOT EXISTS
条件或带有NOT NULL
条件的LEFT JOIN
。 So for your query the possibilities are: 因此,对于您的查询,可能性是:
SELECT *
FROM customer
WHERE id NOT IN
( SELECT customer_id
FROM mailing)
SELECT *
FROM customer c
WHERE NOT EXISTS
( SELECT customer_id
FROM mailing m
WHERE m.customer_id = c.id)
SELECT *
FROM customer c
LEFT JOIN mailing m ON c.id = m.customer_id
WHERE m.customer_id IS NULL
This blog post compares the different possibilities with MySQL 5.1. 这篇博客文章比较了MySQL 5.1的不同可能性。 According to it,
LEFT JOIN / IS NULL
and NOT IN
are faster than NOT EXISTS
. 根据它,
LEFT JOIN / IS NULL
和NOT IN
比NOT EXISTS
快。
However, you should try for yourself which one is the fastest. 但是,您应该自己尝试最快的一个。 That always depends on your data, indexes, ...
这始终取决于您的数据,索引,...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.