0

我有两张桌子:customermailing

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

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

我想要一个 sql 调用来返回所有尚未收到特定邮件的客户。如何 ?

我正在使用 mysql

4

4 回答 4

5
select * from customer where id not in (
    select customer_id from mailing where mailing_id = @mailing_id
)
于 2013-07-18T12:51:55.517 回答
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
)
于 2013-07-18T12:53:15.723 回答
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
于 2013-07-18T12:55:56.457 回答
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

这篇博文比较了 MySQL 5.1 的不同可能性。据它说,LEFT JOIN / IS NULL并且NOT INNOT EXISTS.
但是,您应该自己尝试哪一个是最快的。这始终取决于您的数据、索引、...

于 2013-07-18T13:09:14.810 回答