MySQL中的交集为多个值

用户名

intersect关键字是不能在MySQL中使用。我想知道如何在mysql db中实现以下内容。我的表是:

customer(cid,city,name,state)
orders(cid,oid,date)
product(pid,price,productname)
lineitem(lid,pid,oid,totalquantity,totalprice)

我想要由特定城市“ X”的所有客户购买的产品。也就是说,城市“ x”中的每个客户都应该购买该产品。我设法选择了居住在该特定城市的顾客的oid和pid。现在,我应该选择所有oid中都存在的pid。

例子。

Oid     Pid
2400     1
2400     2
2401     3
2401     1
2402     1
2403     1
2403     3

上述输入的答案应该为1,因为它存在于所有oid中。我用来获取oid和pid的查询:

select t.oid,l.pid
  from lineitem l
  join (select o.oid,c1.cid
          from orders o
          join (select c.cid
                  from customer c
                  where c.city='X') c1
          where o.cid=c1.cid) t on l.oid=t.oid 

现在我需要将所有的oid相交并得到结果。查询不应该依赖于数据。

布莱恩·德米利亚(Brian DeMilia)

尝试:

select pid, count(*)
  from (select t.oid, l.pid
          from lineitem l
          join (select o.oid, c1.cid
                 from orders o
                 join (select c.cid from customer c where c.city = 'X') c1
                where o.cid = c1.cid) t
            on l.oid = t.oid) x
 group by pid
having count(*) = (select count(*)
                     from (select distinct oid
                             from lineitem l
                             join (select o.oid, c1.cid
                                    from orders o
                                    join (select c.cid
                                           from customer c
                                          where c.city = 'X') c1
                                   where o.cid = c1.cid) t
                               on l.oid = t.oid) y) z

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章