mysql - mysql中多个值的交集

标签 mysql sql

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/

相关文章:

mysql - 对维度进行分组的 SQL 场景

sql - MS Access 选择表中的第 N 个最高值

mysql - 在 MySQL 表中拆分数据的好处

.net - .NET 中的连接池

php - 获取每个月的数据

iOS/ swift : directly manipulate remote MySQL over SSH

mysql - 使用 knitr 呈现 SQL 时语法突出显示

php - PDO 类的通用插入方法

sql - 如何使用具有多个结果的子查询将值插入表中?

java - SQL 查询查找与 Toplink 中的日期相等的行