当前位置 : 主页 > 手机开发 > 其它 >

将聚合运算符从SQL转换为关系代数

来源:互联网 收集:自由互联 发布时间:2021-06-22
我写了几个我要转换为关系代数的SQL查询.但是,有些查询使用聚合运算符,我不知道如何转换它们.值得注意的是,他们使用COUNT和GROUP BY .. HAVING运算符. 这是架构: 水手(sid,sname,评级) 储备
我写了几个我要转换为关系代数的SQL查询.但是,有些查询使用聚合运算符,我不知道如何转换它们.值得注意的是,他们使用COUNT和GROUP BY .. HAVING运算符.

这是架构:

水手(sid,sname,评级)
储备(sid,出价,价格)
船(bid,bname)

这是我正在做的一个例子:找到正好由2名水手保留的所有船只的出价和名字.

SELECT B.bid, B.bname
FROM Boats B, Reserves R
WHERE B.bid = R.bid
GROUP BY R.bid
HAVING 2 = (SELECT COUNT(*)
FROM Reserves R2
WHERE R2.bid = B.bid);

允许的关系代数运算:选择,投影,连接,条件连接,重命名,并集,交集,交叉积,除法

这只是答案的一半……

可以使用条件连接和投影找到关系“由两个或更多水手保留的船只”,它们都在您允许的操作集中:

SELECT DISTINCT R1.bid
  FROM Reserves AS R1 
       JOIN Reserves AS R2
          ON R1.bid = R2.bid
             AND R1.sid < R2.sid;

可以使用条件连接(两次)和投影找到关系“由三个或更多水手保留的船只”,它们都在您允许的操作集中:

SELECT DISTINCT R1.bid
  FROM Reserves AS R1
       JOIN Reserves AS R2
          ON R1.bid = R2.bid
             AND R1.sid < R2.sid
       JOIN Reserves AS R3
          ON R1.bid = R3.bid
          AND R2.sid < R3.sid;

如果我们有减号运算符,例如标准SQL中除外:

SELECT DISTINCT R1.bid
  FROM Reserves AS R1 
       JOIN Reserves AS R2
          ON R1.bid = R2.bid
             AND R1.sid < R2.sid
EXCEPT
SELECT DISTINCT R1.bid
  FROM Reserves AS R1
       JOIN Reserves AS R2
          ON R1.bid = R2.bid
             AND R1.sid < R2.sid
       JOIN Reserves AS R3
          ON R1.bid = R3.bid
          AND R2.sid < R3.sid;

如果我们有限制(SQL中的WHERE)和半差异(a.k.a. antijoin)运算符(例如SQL中的NOT IN):

SELECT DISTINCT R1.bid
  FROM Reserves AS R1 
       JOIN Reserves AS R2
          ON R1.bid = R2.bid
             AND R1.sid < R2.sid
 WHERE R1.bid NOT IN (
                      SELECT DISTINCT R1.bid
                        FROM Reserves AS R1
                             JOIN Reserves AS R2
                                ON R1.bid = R2.bid
                                   AND R1.sid < R2.sid
                             JOIN Reserves AS R3
                                ON R1.bid = R3.bid
                                AND R2.sid < R3.sid
                     );

…但您的允许操作集不包括限制,半差或减:(

网友评论