我有两个表:customer
和mailing
:
+==========+ +=============+
| customer | | mailing |
+==========+ +=============+
| id | | id |
+----------+ +-------------+
| name | | customer_id |
+----------+ +-------------+
| mailing_id |
+-------------+
每次我向客户发送邮件时,我都会在邮件表中添加一行邮件ID。一封邮件可以发送给多个客户。
我想要一个sql调用,返回尚未收到某个邮件的所有客户。怎么样?
我正在使用mysql
答案 0 :(得分:5)
select * from customer where id not in (
select customer_id from mailing where mailing_id = @mailing_id
)
答案 1 :(得分:2)
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
)
答案 2 :(得分:2)
像
这样的东西Select c.ID, c.Name
From Customers C
left Join mailing m On c.id = m.customer_id
where m.customer_id is null
答案 3 :(得分:1)
您所描述的内容称为ANTI JOIN
。通常在SQL中有三种不同的方法:带有子查询的NOT IN
条件,带有相关子查询的NOT EXISTS
条件或带有LEFT JOIN
条件的NOT NULL
条件。
因此,对于您的查询,可能性是:
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比较MySQL 5.1的不同可能性。根据它,LEFT JOIN / IS NULL
和NOT IN
比NOT EXISTS
快。
但是,你应该自己尝试哪一个是最快的。这总取决于您的数据,索引......