Is there set division in SQL?

后端 未结 3 1581
清酒与你
清酒与你 2021-01-19 11:19

I\'m fully aware that set division can be accomplished through a series of other operations, so my question is:

Is there a command for set division in SQL?

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-19 11:44

    Here is a nice explanation using relational algebra syntax.

    Given tables sailors, boats and reserves (examples from Ramakrishnan & Gehrke's "Database Management Systems") you can compute sailors who have reserved all boats with the following query:

    SELECT name FROM sailors
    WHERE Sid NOT IN (
        -- A sailor is disqualified if by attaching a boat,
        -- we obtain a tuple  that is not in reserves
        SELECT s.Sid
        FROM sailors s, boats b
        WHERE (s.Sid, b.Bid) NOT IN (
            SELECT Sid, Bid FROM reserves
        )
    );
    
    -- Alternatively:
    SELECT name FROM sailors s
    WHERE NOT EXISTS (
        -- Not reserved boats
        (SELECT bid FROM boats)
        EXCEPT
        (SELECT r.bid FROM reserves r
        WHERE r.sid = s.sid)
    );
    

提交回复
热议问题