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)
My solution is finding student not same advisors , then take negative of this.
Please try with script:
SELECT studid,studname
FROM Student
WHERE studid not in
(
select studid
from
(
SELECT a.studid, b.profid
FROM Advise a
left join
(
SELECT profid
FROM Advise
WHERE studid = '123456789'
) b on b.profid = a.profid
where a.studid not like '123456789'
) x
where x.profid is null
)
group by studid,studname
having count(*) = (SELECT count(profid) FROM Advise WHERE studid = '123456789')
Are you looking for some thing this?
select studname from Student where studid in
(
select studid from (
select studid, GROUP_CONCAT(profid) profs from advice
group by studid having profs in (
select studid, GROUP_CONCAT(profid) profs from advice group by
studid having studid = '123456789'
)
)
)
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.