in Databases recategorized by
6,092 views
25 votes
25 votes

Suppose we have a database consisting of the following three relations.

  • $\text{FREQUENTS (student, parlor)}$ giving the parlors each student visits.
  • $\text{SERVES (parlor, ice-cream)}$ indicating what kind of ice-creams each parlor serves.
  • $\text{LIKES (student, ice-cream)}$ indicating what ice-creams each student likes.

(Assume that each student likes at least one ice-cream and frequents at least one parlor)

Express the following in SQL:

Print the students that frequent at least one parlor that serves some ice-cream that they like.

in Databases recategorized by
6.1k views

2 Comments

What would be the query if the question was:

Print the students that frequent at least one parlor that serves all ice-creams that they like.
0
0

This is my Attempt of your Query Pratik

Select Student

from  frequents F

where NOT EXIST

( Select Student, Parlor, Ice-cream

from F NATURAL JOIN  Likes L

EXCEPT 

select Student, Parlor, Ice-cream

from Serves NATURAL JOIN L);

0
0

4 Answers

49 votes
49 votes
Best answer
SELECT DISTINCT A.student FROM 
    FREQUENTS A, SERVES B, LIKES C
    WHERE
        A.parlor=B.parlor 
        AND
        B.ice-cream=C.ice-cream
        AND
        A.student=C.student;

OR

SELECT DISTINCT A.student FROM FREQUENTS A 
    WHERE
    parlor IN
        (SELECT parlor FROM SERVES B 
            WHERE B.ice-cream IN
                (SELECT ice-cream 
                FROM LIKES C 
                WHERE C.student = A.student));
selected by
by

4 Comments

Will my query work:

select distinct F.student from Frequent F, Serves S
where F.parlour=S.parlour
and S.ice-cream=(Select ice-cream from Likes L, Frequents F
                 where F.student=L.student);

 

0
0
SELECT DISTINCT F.STUDENT FROM FREQUENTS F WHERE F.PARLOUR IN (SELECT PARLOUR FROM SERVES JOIN LIKES)

Is this correct??

0
0

@Gupta731 no it does not work because you are applying where condition incorrectly.

S.ice-cream=(Select ice-cream

   from Likes L, Frequents F 

where F.student=L.student);

the inner query return set of records and you are comparing with single record with ‘=’ that would not possible, it is possible with function IN/NOT IN.

0
0
1 vote
1 vote
select distinct student
from FREQUENTS as f natural join SERVES as s
where icecream in (select icecream 
                   from LIKES as l
                   where f.student = l.student)

 

1 vote
1 vote
SELECT DISTINCT STUDENT
FROM FREQUENT NATURAL JOIN SERVES NATURAL JOIN LIKES ;

 

0 votes
0 votes
Query using EXIST

SELECT Student from FREQUENTS F where EXIST ( SELECT * from SERVES S where F.PARLOR = S.PARLOR AND EXIST (SELECT * FROM LIKES L where S.ICECREAM = L.ICECREAM AND F.STUDENT= L.STUDENT))

Related questions