问题
I have a task at hand which requires me to return the details of a student who is enrolled in a class taught by a teacher with the surname of Hoffman and I'm stuck.
SELECT * FROM Public."Class" WHERE tid=(
SELECT tid FROM Public."Tutor" WHERE tname LIKE '%Hoffman');
This returns to me the classes taught by Hoffman but from here I'm not sure where to go. I believe I have to access the 'Enrolled' table and then finally the student table but have tried to no avail. The following query is as far as I got before breaking the query -_- I'm sure i'll have to use the HAVING
or IN
keyword but I don't quite know what to do with them!
SELECT * FROM Public."Student" WHERE programme='IT' (
SELECT * FROM Public."Class" WHERE tid=(
SELECT tid FROM Public."Tutor" WHERE tname LIKE '%Hoffman')
);
Any help would be much appreciated!
The database structures are as follows:-
Student(sid integer, sname varchar(20), programme varchar(4), level integer, age integer) Class(ccode varchar(6), cname varchar(25), week_day varchar(3), meets_at time, room varchar(6), tid integer) Enrolled(sid integer, ccode varchar(6)) Tutor(tid integer, tname varchar(20))
Thanks again :)
Update:-
SELECT DISTINCT *
FROM Public."Student" s
INNER JOIN Public."Enrolled" e ON e.sid = s.sid
INNER JOIN Public."Class" c ON c.ccode = e.ccode
INNER JOIN Public."Tutor" t ON t.tid = c.tid
WHERE programme='IT' AND t.tname LIKE '%Hoffman';
回答1:
The two solutions above will result in students to be reported multiple times if they are enrolled in multiple classes from the same teacher. If the only goal of the query is to select students only once, the query below will do exactly that.
SELECT *
FROM Student s
WHERE s.programme = 'IT'
AND EXISTS (
SELECT *
FROM Enrolled e
JOIN Class c ON c.ccode = e.ccode
JOIN Tutor t ON t.tid = c.tid
WHERE e.sid = s.sid
AND t.tname LIKE '%Hoffman'
);
回答2:
You don't need to do subqueries for each validation. This could easily be done with JOINS:
SELECT s.*
FROM Student s
INNER JOIN Enrolled e ON e.sid = s.sid
INNER JOIN Class c ON c.ccode = e.ccode
INNER JOIN Tutor t ON t.tid = c.tid
WHERE t.tname LIKE '%Hoffman';
回答3:
You can use joins to solve this instead of subquery
SELECT * FROM Public."Student" s
join Public.Enrolled e on (s.sid= e.id)
join Public.Class c on (c.ccode = e.ccode)
join Public.Tutor t on (c.tid = t.tid)
WHERE s.programme='IT' and t.tname like '%Hoffman'
来源:https://stackoverflow.com/questions/20452655/postgresql-multiple-subqueries