首页 新闻 会员 周边

sql 语句的问题

0
悬赏园豆:10 [已解决问题] 解决于 2015-01-07 15:28

订单详细表orderdetail

orderID,productID,quantity,price

 

其中orderID,productID是组合主键

 

内有productID 表名订单中的商品

 

要求写一个sql 查询出 同时购买 productID 为1和2 的订单ID

 

这个问题 有一些思路,但是不知道好不好。所以希望大家多提供几种思路吧

把sql写出来,然后如果有说明的更好,谢谢大家

算了的主页 算了 | 初学一级 | 园豆:3
提问于:2015-01-07 11:56
< >
分享
最佳答案
0

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)

收获园豆:5
KingMi | 小虾三级 |园豆:1344 | 2015-01-07 13:36
其他回答(3)
0
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
收获园豆:1
凡一二三 | 园豆:85 (初学一级) | 2015-01-07 12:18
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

收获园豆:4
爱编程的大叔 | 园豆:30839 (高人七级) | 2015-01-07 12:37

大叔,你这个语句执行报错的,应该是:

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

支持(0) 反对(0) KingMi | 园豆:1344 (小虾三级) | 2015-01-07 13:39
0

SELECT orderid FROM orderdetail GROUP BY orderid HAVING SUM(CASE WHEN productID=1 THEN 1 WHEN productID=2 THEN 1 END)=2

某猿 | 园豆:373 (菜鸟二级) | 2015-01-07 15:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册