高级MySQL分组查询

时间:2014-11-24 12:38:22

标签: mysql

我有一个在线商店,订单数据库是这样的:

id  purchase_date  buyer_name  buyer_email  product_name  delivery_status
1   10.09.2014     jo smith    jo@smith.com dildo         delivered
2   10.09.2014     jo smith    jo@smith.com superdildo    delivered
3   11.09.2014     john lol    jo@lol.com   cream         delivered
4   13.09.2014     john lol    jo@lol.com   supercream    not delivered
5   15.09.2014     john doe    john@doe.com lingerie      delivered
6   15.09.2014     john doe    john@doe.com lingerie2     not delivered
7   15.09.2014     feels no    ff@trol.com  supercream    delivered
8   18.09.2014     jo smith    jo@smith.com cream         not delivered

我想从此表中选择所有不同的buyer_email,其中 当天所有客户的订单都已“交付”。

我的意思是:

ID 1和2将匹配,查询应输出jo@smith.com,因为他当天所做的两个订单都已交付。

ID 3也是一个匹配项,因为当天(2014年9月11日)发出的所有订单都是jo@lol.com。

在查询中不会匹配ID 4(并非该名称上当天的所有订单都已送达)

ID 5和6也不匹配。

ID 7是匹配

ID 8不匹配。

2 个答案:

答案 0 :(得分:2)

select distinct buyer_email
from your_table
group by buyer_email, purchase_date  
having sum(delivery_status <> 'delivered') = 0

答案 1 :(得分:1)

您希望使用having子句进行聚合。至少要开始。以下内容可以获得完全交付订单的日期和买家:

select o.purchase_date, o.buyer_email
from orders o
group by o.purchase_date, o.buyer_email
having sum(delivery_status <> 'delivered') = 0;

如果您需要订单ID,最简单的方法是使用group_concat()

select o.purchase_date, o.buyer_email, group_concat(o.id) as ids
from orders o
group by o.purchase_date, o.buyer_email
having sum(delivery_status <> 'delivered') = 0;

如果您想要完整的行,可以使用join