[英]generate aggregate results with MySQL select statement
I'm trying to generate a query to tell me how many products were ordered from the site, but in groups. 我正在尝试生成一个查询,以告诉我从站点订购了多少产品,但以组为单位。
This is the structure of my table (product_orders): 这是我的表(product_orders)的结构:
product_order_id | order_id | product_id
168 | 64 | 17
168 | 64 | 18
168 | 64 | 16
168 | 64 | 15
168 | 64 | 19
168 | 65 | 17
168 | 65 | 18
168 | 66 | 16
168 | 66 | 15
168 | 66 | 19
168 | 67 | 15
What I need to be able to get, is a count of orders where the user purchased: 我需要获得的是用户购买的订单数量:
ONLY product_id 17 AND 18 仅product_id 17和18
ONLY product_id 17 AND 16 AND 15 仅product_id 17 AND 16 AND 15
It's that AND that's driving me a bit crazy with this query, and the fact that that 1 order has multiple products. 正是因为AND令我对此查询有些疯狂,而且该1个订单有多种产品。 Any ideas?
有任何想法吗? I'm sure I'm overlooking something simple here.
我确定我在这里忽略了一些简单的事情。
Thanks. 谢谢。 B.
B.
You can do this with a fairly clunky EXISTS
statement 您可以使用相当笨拙的
EXISTS
语句来执行此操作
SELECT COUNT(DISTINCT order_id) FROM product_orders p1
WHERE EXISTS (SELECT * FROM product_orders p2
WHERE p1.order_id = p2.order_id
AND p2.product_id = 17)
AND EXISTS (SELECT * FROM product_orders p3
WHERE p1.order_id = p3.order_id
AND p3.product_id = 18)
AND NOT EXISTS (SELECT * FROM product_orders p4
WHERE p1.order_id = p4.order_id
AND p4.product_id <> 17
AND p4.product_id <> 18);
And you can obviously you repeat this pattern for the {15,16,17}
set. 您显然可以对
{15,16,17}
集重复此模式。
Assuming the product_id's are unique per order in product_orders table, we can count matching and non-matching and compare. 假设product_id在product_orders表中每个订单都是唯一的,我们可以计算匹配和不匹配的数量并进行比较。 So there should be exactly two entries with product_id 17 or 18, and none that are not 17 or 18 to match the first scenario.
因此,应该恰好有两个具有product_id 17或18的条目,并且都不是不是17或18的条目以匹配第一种情况。 The second scenario would be the same logic, except there should be exactly three entries with product_id 15 or 16 or 17, and none that don't match any:
第二种情况是相同的逻辑,除了应该存在三个完全相同的条目,它们的product_id为15或16或17,并且没有一个与任何条目都不匹配:
select count(*) from (
select distinct order_id from product_orders po1
where (
(select count(product_id) from product_orders po2
where po1.order_id = po2.order_id and
po2.product_id in (17, 18)) = 2
and
(select count(product_id) from product_orders po3
where po1.order_id = po3.order_id and
po3.product_id not in (17, 18)) = 0
) or (
(select count(product_id) from product_orders po4
where po1.order_id = po4.order_id and
po4.product_id in (15, 16, 17)) = 3
and
(select count(product_id) from product_orders po5
where po1.order_id = po5.order_id and
po5.product_id not in (15, 16, 17)) = 0
)
) p
There is only one order that satisfies all the conditions: order_id 65. 只有一个满足所有条件的订单:order_id 65。
Working Demo: http://sqlize.com/5Q5Lo7Oa71 工作演示: http : //sqlize.com/5Q5Lo7Oa71
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.