mysql - 如何在mysql中使用where exists or not exists实现相交

标签 mysql sql database relational-database intersection

我的表是:

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

我想选择城市'X'的所有客户购买的产品。这意味着我需要与居住在城市'X'的所有客户购买的产品相交

示例:如果有 3 个客户 c1、c2 和 c3,我的答案是 c1.product(intersect)c2.product(intersect)c3.product

我只想使用 where existswhere not exists 来实现它,因为我需要为 where not in< 编写关系演算where in 不可用。我的部分查询是这样的:

select 
  * 
from 
  product p,
  lineitem l,
  customer c1 
where 
  exists(
   select 
      * 
   from 
     customer c,
     orders o 
   where 
    o.cid=c.cid and 
    c.city='X' and 
    l.oid=o.oid and 
    l.pid=p.pid and 
    c1.cid=c.cid)

上面的查询给出了居住在城市 X 的所有客户的 pid、cid、oid、lid、totalprice、city、productname。现在我需要弄清楚如何选择所有客户共有的产品。

注意:

我不能使用任何聚合函数,因为它在关系演算中不可用。我有一个使用聚合函数的有效查询,那就是

select 
   p.productname 
from 
   product p, 
   orders s, 
   lineitem l, 
   customer c 
where 
   l.pid=p.pid and
   l.oid=s.oid and 
   c.cid=s.cid and 
   c.city='X' 
group by 
   p.productname 
having 
   count(distinct c.cid)=(select count(*) from customer c1 where c1.city='X')

如果有人可以在 where existswhere not exists 形式中转换上面的查询而不需要 countgroup by< 就可以了.

我确信它可以完成,因为我可以在关系代数中根据 Codd's theorom 做到这一点元组关系演算和关系代数在逻辑上是等价的,任何一个表达的查询都可以用另一个表达。由于关系代数和关系演算都不支持聚合函数,所以查询可以用没有聚合函数的sql表达。

最佳答案

这是我的答案。

我在 http://www.sqlfiddle.com/#!2/f2fb85/1 创建了一个 sqlfiddle , 所以你可以试试。

查询是:

SELECT p.*
FROM product p
WHERE NOT EXISTS (
    SELECT c.cid
    FROM customer c
    WHERE NOT EXISTS (
        SELECT l.lid
        FROM lineitem l
        JOIN orders o ON o.oid = l.oid
        WHERE l.pid = p.pid
        AND o.cid = c.cid
    )
    AND c.city = 'X'
) AND EXISTS (
    SELECT c.cid
    FROM customer c
    WHERE c.city = 'X' 
)

关于mysql - 如何在mysql中使用where exists or not exists实现相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22315743/

相关文章:

MySql 无法将一个表中的值添加到另一个表中

java - 检查 Java 中的 MySQL DB 中是否存在值?

SQL:将 SELECT 输出提供给 LIKE

java - 在 Vaadin Flow 中处理登录和授权的最佳方法?

SQL 查询 : joining 3 tables with multiple values

MySQL IF Case Exists 检查用户是否已附加

mysql - 如何修复插入后触发计数时mysql代码中的错误

sql - 如何查看 Oracle 数据库中 VPD 添加的谓词?

MySQL 行锁定 myisam innodb

mysql - Golang 使用 JOIN 查询多个数据库