有一个包含重复数据的表格,我可以使用此查询对电子邮件进行分组
SELECT id, first_name, email, status FROM customers WHERE status = '0' GROUP BY email
但是,我不想选择已经拥有状态=' 1'
的重复电子邮件的客户表格设计如下......
id first_name email status
1 Tony tony@gmail.com 0
2 Terry terry@gmail.com 0
3 Alex alex@gmail.com 0
4 John john@gmail.com 0
5 Mike mike@gmail.com 1
6 Mike Jones mike@gmail.com 0
7 Mike Fake mike@gmail.com 0
我的查询仍然选择mike@gmail.com,因为状态为0,但实际上已经有状态= 1 ....我怎么不选择已经拥有状态的电子邮件= 1?
答案 0 :(得分:1)
试试这个:
使用 LEFT JOIN
SELECT c.id, c.first_name, c.email, c.status
FROM customers c
LEFT OUTER JOIN customers c1 ON c.email = c1.email AND c1.cstatus = 1
WHERE c.status = 0 AND c1.id IS NULL
GROUP BY c.email;
使用 NOT EXISTS
SELECT c.id, c.first_name, c.email, c.status
FROM customers c
WHERE c.status = 0 AND
NOT EXISTS (SELECT 1 FROM customers c1 WHERE c.email = c1.email AND c1.cstatus = 1)
GROUP BY c.email;
答案 1 :(得分:1)
最简单的方法是使用not exists
select c.* from customers c where not exists
(
select 1 from customers c1
where c1.email = c.email
and c1.status = 1
)
答案 2 :(得分:0)
SELECT id, first_name, email, status,
COUNT(CASE WHEN status = '0' THEN 1 END) AS zero_status_count
COUNT(CASE WHEN status = '1' THEN 1 END) AS one_status_count
FROM customers GROUP BY email having zero_status_count > 0 and one_status_count < 1;
试试这个。