So I am given this question:
Consider the following tables where keys are bolded: Professor(profid, profname, department) Student(studid, studname, major), and Advise(profid, studid).
Return the names of the students who have exactly the same advisors as student whose id is '123456789'.
The query that I came up with doesn't return the exact same advisors, but rather the advisors that are common between student 123456789 and other students. An example is if student 123456789 has advisors 1 and 2, and student 5 only has advisor 1, my current query will return student 5, which is incorrect. The query is only supposed to return students that have both advisors 1 and 2. Here is my query so far:
SELECT studname
FROM Student
WHERE studid IN
(
SELECT DISTINCT studid
FROM Advise
WHERE profid IN
(
SELECT profid
FROM Advise
WHERE studid = '123456789'
)
);
How can I get this query to return the exact list of students that advise student 123456789?
I test it run right. You can try:
SELECT a.studid, b.studname
FROM (
SELECT studid, COUNT(studid) AS numstud
FROM Advise
WHERE
profid IN (
SELECT profid FROM Advise WHERE studid = 123456789
) AND
studid NOT IN (
SELECT studid FROM Advise WHERE profid NOT IN (
SELECT profid FROM Advise WHERE studid = 123456789
)
)
GROUP BY studid
HAVING numstud = (SELECT COUNT(*) FROM Advise WHERE studid = 123456789)
) AS a LEFT JOIN Student AS b ON (a.studid = b.studid)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With