我需要找到类所有拥有英语和数学书籍的学生。
表结构简单
Student
==========================
id | First Name | Last Name
1 | Akhil | Kumar
2 | Nikhil | Tylagi
3 | Pawan | Benarjee
Student Books
==========================
id | student_id | book
1 | 1 | Eng
2 | 2 | Maths
3 | 3 | Physics
4 | 1 | Maths
5 | 2 | Physics
6 | 3 | Eng
我能够创建的是:
SELECT student_id
from student_books OStu
WHERE book = "Eng" AND (SELECT book FROM student_books
WHERE book = "Maths" AND student_id = OStu.student_id);
从上面来看,Akhil 只是一个应该被取回的人
Expected Result should be
=====================================
student_id | First Name | Last Name
=====================================
1 | Akhil | Kumar
现在的问题是,如果有人想查询拥有(英语、数学、物理最多可以说 30 本书)的学生怎么办。
有没有更好的方法呢? (<-- 我的意思是,我是否必须重新考虑我的设计方法?因为,我可能需要多达 30 本书的相同东西)
最佳答案
您可以使用 HAVING
子句来过滤那些同时拥有 Maths
和 ENG
的人:
SELECT t.student_id
FROM student_books t
WHERE t.Book IN('Maths','Eng')
GROUP BY t.student_id
HAVING COUNT(distinct t.book) = 2
如果你还想要他们的名字:
SELECT s.first_name,s.last_name,t.student_id
FROM student_books t
INNER JOIN Student s
ON(t.student_id = s.id)
WHERE t.Book IN('Maths','Eng')
GROUP BY t.student_id, s.first_name,s.last_name
HAVING COUNT(distinct t.book) = 2
如果您想要其他书籍,只需使用 WHERE
和 HAVING
,将它们更改为 3:
WHERE t.Book IN('Maths','Eng','Physics')
HAVING COUNT(distinct t.book) = 3
关于mysql - SQL查询以查找具有两个或多个特定主题的所有学生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37699346/