我有两张桌子:
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
)
学生John
,Mimi
甚至不会被考虑,因为他们没有注册三个科目。
我知道我可以使用 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,则我丢弃结果并再次运行第一个查询。
我将如何在一个查询中尝试此操作?