我有一个包含此格式数据的表格。
+-----+----------+------------+------------+
| id | grade_id | student_id | subject_id |
+-----+----------+------------+------------+
| 249 | 1 | 27 | 1 |
| 250 | 1 | 27 | 2 |
| 251 | 1 | 27 | 4 |
| 252 | 1 | 28 | 1 |
| 253 | 1 | 28 | 2 |
| 254 | 1 | 28 | 4 |
| 255 | 1 | 29 | 1 |
| 256 | 2 | 29 | 2 |
| 257 | 3 | 29 | 4 |
+-----+----------+------------+------------+
我需要所有的subject_id对所有subject_id都有grade_id = 1,我将使用哪个查询来获取student_id。
我需要查询的结果应该是这样的吗?
student_id数据
27
28
答案 0 :(得分:1)
在MySQL中:
SELECT student_id FROM table WHERE student_id NOT IN (SELECT students_id FROM table WHERE grade_id != 1)
在Django中:
from django.db.models import Q
not_eligible = Model.objects.all().filter(~Q(grade_id = 1))
.values('student_id').distinct()
eligible = Model.objects.all().filter(~Q(student_id_in = not_eligible))
.values('student_id').distinct())
# eligible -> all student_id