Mysql选择列中只有指定值的行
嗨,我有一个名为student\u subject\u table的mysql表:Mysql选择列中只有指定值的行,mysql,Mysql,嗨,我有一个名为student\u subject\u table的mysql表: +----+-------------+---------------------+ | id | student_id | subject | +----+-------------+---------------------+ | 1 | 7 | math | | 2 | 7 | physics
+----+-------------+---------------------+
| id | student_id | subject |
+----+-------------+---------------------+
| 1 | 7 | math |
| 2 | 7 | physics |
| 3 | 7 | chemistry |
| 8 | 8 | math |
| 9 | 8 | physics |
| 10 | 8 | chemistry |
| 11 | 8 | biology |
+----+-------------+---------------------+
我正在努力获得那些只学数学、物理和化学的学生的身份证
我在条款中试过:
select student_id
from student_subject table
where
subject in ('math', 'physics', 'chemistry')
GROUP BY (student_id)
正如所料,我的学生id是7和8。
在上表中,我只需要student_id=7
mysql中有什么方法可以做到这一点吗
请提供帮助。您可以使用以下查询:
select student_id
from student_subject table
group by student_id
having
SUM(subject IN ('math', 'physics', 'chemistry')) = COUNT(DISTINCT subject)
AND COUNT(DISTINCT subject)=3
学生7和8的成绩都是3分SUM(数学、物理、化学科目)
学生7为3,学生8为4计数(不同科目)
(学生id,科目)
是唯一的,您可以用COUNT(*)替换COUNT(DISTINCT…
)
只返回学生7。使用DISTINCT子句
SELECT DISTINCT student_id
FROM student_subject_table
WHERE subject IN ('math', 'physics', 'chemistry')
GROUP BY (student_id);