[英]SQL query to return an exact list of subquery
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 ). 考虑以下表键进行加粗:教授(PROFID,profname,系)学生(studid,studname,主要),并建议(PROFID,studid)。
Return the names of the students who have exactly the same advisors as student whose id
is '123456789'. 返回与
id
为“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. 我提出的查询并没有返回完全相同的顾问,而是返回学生123456789和其他学生之间共同的顾问。 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.
例如,如果学生123456789有顾问1和2,而学生5只有顾问1,我当前的查询将返回学生5,这是不正确的。 The query is only supposed to return students that have both advisors 1 and 2. Here is my query so far:
该查询只能返回同时拥有顾问1和2的学生。这是我目前的查询:
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? 如何才能获得此查询以返回建议学生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'
)
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.