intersect
关键字在 mysql 中不可用。我想知道如何在 mysql db 中实现以下内容。我的 table 是:
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 进行相交并获取结果。查询不应依赖于数据。
最佳答案
尝试:
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
关于mysql - mysql中多个值的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21870140/