用于连接的SQL语句,但不在其他表中

时间:2013-07-18 12:48:38

标签: mysql sql select

我有两个表:customermailing

+==========+  +=============+
| customer |  | mailing     |
+==========+  +=============+
| id       |  | id          |
+----------+  +-------------+
| name     |  | customer_id |
+----------+  +-------------+
              | mailing_id  |
              +-------------+

每次我向客户发送邮件时,我都会在邮件表中添加一行邮件ID。一封邮件可以发送给多个客户。

我想要一个sql调用,返回尚未收到某个邮件的所有客户。怎么样?

我正在使用mysql

4 个答案:

答案 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 NULLNOT INNOT EXISTS快。
但是,你应该自己尝试哪一个是最快的。这总取决于您的数据,索引......