我的表格如下:
customer(cid,name,city,state)
orders(oid,cid,date)
product(pid,productname,price)
lineitem(lid,pid,oid,number,totalprice)
我希望能够选择所有在城市“X”居住的客户购买的产品。这意味着我需要取交集,即所有居住在城市'X'的客户购买的产品。
例如:如果有三个客户c1,c2和c3,则我的答案是c1.product(交集)c2.product(交集)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)
上面的查询给我提供了城市X中所有客户的pid、cid、oid、lid、总价格、城市、产品名称。现在我需要弄清楚如何选择所有客户共同拥有的产品。
注意:
我不能使用任何聚合函数,因为在关系演算中不可用。我有一个使用聚合函数的工作查询,那就是:
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 exists
或where not exists
形式,而不使用count
和group by
,那么没问题。
我相信这是可能的,因为我可以在关系代数中做到这一点,并且根据科德定理,元组关系演算和关系代数在逻辑上是等价的,任何在其中一个中表达的查询都可以在另一个中表达。由于关系代数和关系演算都不支持聚合函数,查询可以在sql中表达而不使用聚合函数。