永发信息网

求问SQL查询同时满足多个值的数据。

答案:2  悬赏:0  手机版
解决时间 2021-12-21 07:55
  • 提问者网友:两耳就是菩提
  • 2021-12-21 02:25
会员表

表结构:
会员表:member_id
订单表:order_id,member_id
订单产品表:order_product_id,product_id,order_id

现在想知道购买了某些产品的会员(member_id)。
怎么写sql.比如想知道哪些会员同时购买了product_id (1,2,3,4,5 )

现在我是
SELECt member_id FROM 会员表 EXISTS(SELECt product_id from 订单产品表,订单表 where 订单表.member_id = 会员表.member_id and 订单表.order_id=订单产品表.order_id and 订单产品表.product_id in( 1,2,3,4,5 ))

上面的SQL只买一件也会成立。
但是我是想买过1,2,3,4,5这五件的产品的会员。
最佳答案
  • 五星知识达人网友:行雁书
  • 2021-12-21 03:04
可以把语句改成:
SELECt member_id FROM 会员表 EXISTS(SELECt product_id from 订单产品表,订单表 where 订单表.member_id = 会员表.member_id and 订单表.order_id=订单产品表.order_id and
(
订单产品表.product_id = 1
and 订单产品表.product_id = 2
and 订单产品表.product_id = 3
and 订单产品表.product_id = 4
and 订单产品表.product_id = 5
)
全部回答
  • 1楼网友:渊鱼
  • 2021-12-21 03:26
你的代码中“订单产品表.product_id in( 1,2,3,4,5 )”的意思是产品的id属于这个集合就算满足条件。事实要满足5中产品都有。如果只有5中产品,有一种方法可以用count函数,count(distinct column_name) =5,如果产品数目大于5的话,如果有n种,那就必须用类似这种句型select member_id from 会员表,会员表 会员表1 ,会员表 会员表2 ,会员表 会员表3,…… where …… and where(select (cout (distinct product_id)=5)) 。给你个列子: 1、检索所有课程都选修的的学生的学号与姓名 select xh,xm from s where not exists (select * from c where not exists (select * from e where xh=s.xh and kh=c.kh ) ) 2、检索同时选修了课程“”和课程“”的学生学号和姓名 select distinct s.xh,s.xm from s,e,e f where e.xh=f.xh and s.xh=e.xh and e.kh='08305001' and f.kh='08305002' e f 表示与e表相同数据的一张表分f。kh表示课程id。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯