简体   繁体   中英

MySQL Correlated Query Confusion

Jumping right in, here is the MySQL query that isn't working:

SELECT S.pub
FROM serves S
WHERE NOT EXISTS (  SELECT L.beer
                    FROM likes L
                    WHERE L.drinker = "Joe" AND L.beer NOT IN ( SELECT S.beer
                                                                FROM S));

The intent of this query is to select pubs that serve all the beers that Joe likes. However, when I try to execute it, I get an error saying that table S does not exist (as caused by "SELECT S.beer FROM S"). But I aliased S to an instance of the serves table in the outer FROM clause. What am I doing wrong?

Also it seems overly complicated to me that I am using NOT EXISTS and NOT IN. Is there a more elegant way of structuring this query?

Here is the database schema by the way:

LIKES(drinker,beer);
FREQUENTS(drinker,pub);
SERVES(pub,beer,cost);

Also, this question is related to my homework, so please take that into account when answering the question. Thank you.

You should use join

SELECT S.pub FROM  SERVES S INNER JOIN LIKES L ON L.drinker = "Joe" AND L.beer= S.beer;

I think this will helps your problem OR

You can use this

SELECT S.pub
    FROM serves S
    WHERE NOT EXISTS (  SELECT L.beer
                        FROM likes L
                        WHERE L.drinker = "Joe" AND L.beer IN ( SELECT SS.beer
                                                                    FROM serves SS));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM