use*_*360 7 mysql sql database intersection relational-database
我的表是:
customer(cid,name,city,state)
orders(oid,cid,date)
product(pid,productname,price)
lineitem(lid,pid,oid,number,totalprice)
Run Code Online (Sandbox Code Playgroud)
我想选择城市'X'的所有客户购买的产品.这意味着我需要交叉生活在城市'X'的所有客户购买的产品
示例:如果有3个客户c1,c2和c3我的答案是c1.product(intersect)c2.product(intersect)c3.product
我想实现这个只是使用where exists
或where 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)
Run Code Online (Sandbox Code Playgroud)
以上查询为我提供了生活在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')
Run Code Online (Sandbox Code Playgroud)
如果有人可以在没有和转换上面的查询where exists
或where not exists
形式,这是没关系的.count
group by
我确信它可以完成,因为我可以在关系代数中做到这一点,并且根据Codd的理论元组关系演算和关系代数在逻辑上是等价的,并且在一个中表达的任何查询都可以在其他中表达.作为关系代数和关系代数不支持聚合函数,查询可以在没有聚合函数的情况下用sql表示.
select * from product p where not exists(\n select *\n from customer c\n where c.city = \'x\'\n and not exists (\n select *\n from lineitem l\n where l.pid = p.pid\n and exists (\n select *\n from orders o\n where o.oid = l.oid\n and o.cid = c.cid\n )\n )\n )\n
Run Code Online (Sandbox Code Playgroud)\n\n关系演算:
\n\n{T| \xe2\x88\x83p\xd0\x84product (\xc2\xac(\xe2\x88\x83c\xd0\x84customer(c.city="Newark")^\xc2\xac(\xe2\x88\x83l\xd0\x84lineitem(l.pid=p.pid)^\xe2\x88\x83o\xd0\x84orders(o.oid=l.oid^o.cid=c.cid))))}\n
Run Code Online (Sandbox Code Playgroud)\n\n关系代数:
\n\n