SQL查询:获取产品大于1的订单

时间:2020-11-12 16:35:18

标签: mysql sql count aggregate-functions having-clause

Orders Table

psa_psofk是订单ID,psa_prdfk是产品ID。我只想要具有多个产品的订单,即我不想要订单1和5。

1 个答案:

答案 0 :(得分:1)

您可以使用group byhaving

select psa_psofk 
from mytable 
group by psa_psofk 
having count(*) > 1

这假定没有重复的(psa_psofk, psa_prdfk)。否则,您需要将having子句更改为:

having count(distinct psa_prdfk) > 1

如果要整行,则一个选项使用exists

select t.*
from mytable t
where exists (
    select 1 
    from mytable t1 
    where t1.psa_psofk = t.psa_psofk and t1.psa_prdfk <> t.psa_prdfk
)