How to select all subjects that are taken by all students such that all students took grade > 50 in them

时间:2015-10-06 08:21:55

标签: mysql

I have a table called records containing 3 columns: student, subject and grade

Each {x,y,z} entry in the table means student x took class y with grade z. If student x didn't take class y then the entry doesn't exist in the table. So this table is like a university record of all students and the subjects taken by them.

I want to select all subjects that are taken by all students such that the grades of all students in these subjects are above 60.

I tried creating the table

CREATE TABLE temp SELECT subject FROM records WHERE grade > 60;

Then I used temp to create a new table that has subject and count, where count counts the number of students that took that subject, and then I deleted all rows that have count< number of students. But I know this is very inefficient.

How can I do this more efficiently using MySQL ?
Also if you can provide me with good MySQL resource/tutorial link so that I can practice, I would be thankful. I am new to MySQL and I am working on large databases and I need to make my queries more efficient and straight forward.

2 个答案:

答案 0 :(得分:0)

How about

SELECT subject FROM records 
WHERE subject NOT IN
(
SELECT subject FROM records 
WHERE grade <=60
)
AND subject IN
(
SELECT subject FROM records
GROUP BY subject
HAVING count(*) = (SELECT COUNT(DISTINCT student) FROM records)
)

As further reading I'd recommend this and this

EDITED: now includes "subjects taken by ALL students"

答案 1 :(得分:0)

I would use the no exists clause because it simply confirms if there are no records within the subquery, but will not try to obtain the resultset. It is more effective than a not in clause.

SELECT subject FROM records r1
WHERE subject NOT EXISTS
(
SELECT 1 FROM records r2 
WHERE r2.subject=r1.SUBJECT AND grade<=60
)