订单详细表orderdetail
orderID,productID,quantity,price
其中orderID,productID是组合主键
内有productID 表名订单中的商品
要求写一个sql 查询出 同时购买 productID 为1和2 的订单ID
这个问题 有一些思路,但是不知道好不好。所以希望大家多提供几种思路吧
把sql写出来,然后如果有说明的更好,谢谢大家
select orderid from 订单主表 as t where (可以先给个时间范围控制)
exists(Select 1 from orderdetail where productid=1 and orderid=t.orderid)
and exists(Select 1 from orderdetail where productid=2 and orderid=t.orderid)
select * from ( select orderID, (select count(*) from orderdetail as innerTable where innerTable. orderID=orderdetail.orderID and innerTable.productId=1 ) as c1, (select count(*) from orderdetail as innerTable where innerTable. orderID=orderdetail.orderID and innerTable.productId=2 ) as c2 from orderdetail group by orderID )as tt where c1>0 and c2>0
select orderid from
(Select orderid from orderdetail where productid=1)M
inner join (select orderid from orderdetail where productid=2)N
on M.orderid=N.orderid
大叔,你这个语句执行报错的,应该是:
select m.orderid from
(Select orderid from orderdetail where productid=1) M
inner join (select orderid from orderdetail where productid=2) N
on M.orderid=N.orderid
SELECT orderid FROM orderdetail GROUP BY orderid HAVING SUM(CASE WHEN productID=1 THEN 1 WHEN productID=2 THEN 1 END)=2