[英]MySQL - Return rows only if all the values in WHERE clause are present
I have a database that stores exam records: tbl_exams
stores the id and name of exams - there are only 9 exams and so only 9 records in this table as the exams are fixed and do not change. 我有一个存储考试记录的数据库:
tbl_exams
存储考试的ID和名称-只有9项考试,因此该表中只有9条记录,因为考试是固定的且不会更改。 tbl_exam_details
stores all the details for an exam entry, and includes the corresponding id from tbl_exams
- there is a foreign key constraint for this. tbl_exam_details
存储考试条目的所有详细信息,并包括来自tbl_exams
的相应tbl_exams
存在外键约束。 What I'm trying to do is create a query that returns rows only if all 9 exams have been taken by a certain student and the pass_or_fail
field is '1' - I use tinyint(1)
to store 1 which is pass, or 0 which is fail). 我要尝试做的是创建一个查询,该查询仅在某个学生参加了全部9项考试并且
pass_or_fail
字段为'1'时才返回行-我使用tinyint(1)
来存储1个合格或0失败)。 This is essentially to check if all 9 exams have been passed. 这实际上是检查是否所有9项考试均已通过。
This is what I have so far, however it is returning rows even when the student has only completed one or two exams: 这是我到目前为止的内容,但是即使学生仅完成一两次考试,它仍会返回行:
SELECT tbl_exam_details.student_id, exam_name, exam_date, pass_or_fail FROM tbl_exam_details
INNER JOIN tbl_exams ON tbl_exams.exam_id = tbl_exam_details.exam_id
WHERE student_id = 1 AND pass_or_fail = 1
AND tbl_exam_details.exam_id IN (1, 2, 3, 4, 5, 6, 7, 8, 9)
ORDER BY exam_details_id
What I need is for the query to only return rows once all 9 exams have been passed. 我需要的是查询仅在全部9个考试都通过后才返回行。 So, if a student has passed 8 exams, the query should return 0 rows.
因此,如果学生已通过8项考试,则查询应返回0行。 If anyone could help me out it would be greatly appreciated.
如果有人可以帮助我,将不胜感激。
SELECT ted.student_id,
exam_name,
exam_date,
pass_or_fail
FROM tbl_exam_details ted
INNER JOIN tbl_exams
ON tbl_exams.exam_id = ted.exam_id
WHERE student_id = 1
AND (SELECT COUNT(*)
FROM tbl_exam_details ted2
WHERE ted2.pass_or_fail = 1
AND ted2.student_id = ted.student_id
) = 9 -- mean this student pass 9 exams
ORDER BY exam_details_id
Is this what you want? 这是你想要的吗?
SELECT ed.student_id
FROM tbl_exam_details ed
WHERE ed.student_id = 1 AND ed.pass_or_fail = 1 AND
ed.exam_id IN (1, 2, 3, 4, 5, 6, 7, 8, 9)
GROUP BY ed.student_id
HAVING COUNT(*) = 9; -- or maybe COUNT(DISTINCT exam_id) = 9
This returns the student ids that have passed the 9 exams. 这将返回已通过9次考试的学生ID。 It doesn't include any other information.
它不包含任何其他信息。
You can group_concat for a full list... 您可以group_concat查看完整列表...
select x1.*
from
(
select t1.*, group_concat(distinct exam_id order by exam_id separator '|') as x_list
from tbl_exam_details t1
where pass_or_fail = 1
group by student_id
) x1
where x_list = '1|2|3|4|5|6|7|8|9'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.