Converting aggregate operators from SQL to relational algebra

前端 未结 3 1664
抹茶落季
抹茶落季 2020-12-18 13:56

I have several SQL queries written that I want to convert to relational algebra. However, some of the queries use aggregate operators and I don\'t know how to convert them.

3条回答
  •  心在旅途
    2020-12-18 14:12

    This is only half an answer...

    The relation "boats reserved by two or more sailors" can be found using conditional join and projection, which are both in your set of allowed operations:

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

    The relation "boats reserved by three or more sailors" can be found using conditional join (twice) and projection, which are both in your set of allowed operations:

    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;
    

    If we had a minus operator e.g. EXCEPT in Standard 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;
    

    If we had restriction (WHERE in SQL) and a semi difference (a.k.a. antijoin) operator (e.g. NOT IN in SQL):

    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
                         );
    

    ...but your set of allowed operations does not include restriction, semi difference or minus :(

提交回复
热议问题