mysql中的交叉点用于多个值

时间:2014-02-19 03:00:16

标签: mysql sql

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并得到结果。查询不应该依赖于数据。

2 个答案:

答案 0 :(得分:1)

尝试:

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

答案 1 :(得分:0)

我认为您可以使用 IN

来达到您想要的效果