mysqlsqlrelational-divisionnot-existssql-except

EXCEPT command - Find sailors who’ve reserved all boats


I am reading a textbook and I do not understand this query: Find sailors who’ve reserved all boats.

For the query, Find sailors who’ve reserved all boats, the answer given is:

SELECT  S.sname
FROM  Sailors S
WHERE  NOT EXISTS 
          ((SELECT  B.bid
             FROM  Boats B)
            EXCEPT
             (SELECT  R.bid
              FROM  Reserves R
              WHERE  R.sid=S.sid))

My questions are:

  1. Is there something wrong with the above query? When I put it into MySQL Workbench, it shows I have syntax error with the EXCEPT

  2. Beside the solution given by the book above, is there any other way to do the query: Find sailors who’ve reserved all boats

Thank you,


Solution

  • You can do this using COUNT and CONCAT. This query selects the sailors that are paired (in the Reserves table) with each boat in the boat table:

    SELECT Sailors.name
    FROM Sailors INNER JOIN
    (SELECT Reserves.sid
     FROM Reserves
     GROUP BY Reserves.sid
     HAVING COUNT(DISTINCT CONCAT(Reserves.sid, Reserves.bid)) =
     (SELECT COUNT(DISTINCT Boats.bid)
      FROM Boats)) sub
    ON Sailors.sid = sub.sid
    

    Tested here: http://sqlfiddle.com/#!9/82005/2