2

我有两张桌子:

 Students         Student_Grades
   V------------------------V
+----+------+    +----+------------+---------+-------+
| id | name |    | id | student_id | subject | grade |
+----+------+    +----+------------+---------+-------+
| 0  | Dave |    | 0  | 0          | Math    | 100   |
+----+------+    +----+------------+---------+-------+
| 1  | John |    | 1  | 0          | Chem    | 90    |
+----+------+    +----+------------+---------+-------+
| 2  | Kate |    | 2  | 0          | CompSCI | 95    |
+----+------+    +----+------------+---------+-------+
| 3  | Mimi |    | 3  | 1          | ELA     | 98    |
+----+------+    +----+------------+---------+-------+
                 | 4  | 2          | Biology | 92    |
                 +----+------------+---------+-------+
                 | 5  | 2          | Chem    | 94    |
                 +----+------------+---------+-------+
                 | 6  | 2          | Math    | 98    |
                 +----+------------+---------+-------+
                 | 7  | 3          | Math    | 100   |
                 +----+------------+---------+-------+ 

我想从注册三个以上科目的随机学生中选择所有科目和成绩。(要么Dave要么Kate

学生JohnMimi甚至不会被考虑,因为他们没有注册三个科目。

我知道我可以使用 PHP 来实现这一点,但我希望通过对数据库的一次查询来完成。

SELECT * FROM Students t JOIN (SELECT CEIL(MAX(ID)*RAND()) AS ID FROM Students) AS x ON t.ID >= x.ID LIMIT 1

通过上面的查询,我随机选择了一个学生,我可以进去检查他们是否有三个科目SELECT count(subjects) FROM Students WHERE id=random_id

如果返回的计数低于 3,则我丢弃结果并再次运行第一个查询。

我将如何在一个查询中尝试此操作?

4

1 回答 1

2

这是经过测试和工作的:

SELECT * 
FROM Students s 
JOIN (
    SELECT student_id 
    FROM Student_Grades 
    GROUP BY student_id 
    HAVING COUNT(*) >= 3 
    ORDER BY RAND() 
    LIMIT 1
) rs 
    ON rs.student_id = s.id 
JOIN 
    Student_Grades sg 
    ON sg.student_id = s.id

这是 SQL 小提琴:http ://sqlfiddle.com/#!2/e5b5b/1

于 2013-06-24T04:56:47.833 回答