sql—在GROUPBY操作上添加where子句

a0zr77ik  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(360)

此查询列出了woocommerce中订购了两种产品中任何一种产品的不同订单号,其中订单处于名为“wc on hold”的状态。查询确实可以工作,但是如果我在and count(t1.id)=2中返回注解,它将失败,并且组函数的使用无效。如果我将where语句改为having,它仍然会失败并出现语法错误。

select distinct t1.id, count(t1.ID) as Products from wp_posts t1
inner join wp_woocommerce_order_items t2 on t1.ID = t2.order_id
inner join wp_woocommerce_order_itemmeta t3 on t2.order_item_id = t3.order_item_id
where t3.meta_key = '_product_id' and (t3.meta_value=19549 or t3.meta_value=19547)
and t1.post_status='wc-on-hold'
--and count(t1.ID)=2
group by t1.id
order by count(t1.ID) asc
4bbkushb

4bbkushb1#

你试的时候把having子句放在哪里了?having子句必须在groupby之后和order by之前。所以是这样的:

select distinct t1.id, count(t1.ID) as Products from wp_posts t1
inner join wp_woocommerce_order_items t2 on t1.ID = t2.order_id
inner join wp_woocommerce_order_itemmeta t3 on t2.order_item_id = t3.order_item_id
where t3.meta_key = '_product_id' and (t3.meta_value=19549 or t3.meta_value=19547)
and t1.post_status='wc-on-hold'
group by t1.id
having count(t1.id) = 2
order by count(t1.ID) asc
j2qf4p5b

j2qf4p5b2#

听起来像是一场灾难 having 条款就是你想要的。我将你的问题表述为:

select p.id, count(*) as no_products 
from wp_posts p
inner join wp_woocommerce_order_items oi 
    on p.ID = oi.order_id
inner join wp_woocommerce_order_itemmeta oim 
    on oi.order_item_id = oim.order_item_id
where 
    oim.meta_key = '_product_id' 
    and oim.meta_value in (19549, 19547)
    and p.post_status = 'wc-on-hold'
group by p.id
having count(*) = 2
order by p.id

笔记:
这个 having 子句位于 group by 条款
有意义的表别名使查询更容易理解 in 可以方便地根据值列表检查同一列 count(*) 效率比 count(<column>) (在这里,它在功能上是等效的)
按计数排序是没有用的,因为您已经对它进行了筛选(所有行都有相同的计数)

相关问题