我试图得到所有的课程,其中只有"module=5",任何不同的课程。如你所见,我有4门课程,如2,3,4,5,但只有两门课程只有"module=5",例如课程2,5。
+----+--------+--------+
| id | course | module |
+----+--------+--------+
| 1 | 2 | 5 |
| 2 | 3 | 5 |
| 3 | 3 | 11 |
| 4 | 4 | 5 |
| 5 | 4 | 3 |
| 6 | 5 | 5 |
| 7 | 4 | 6 |
| 8 | 4 | 5 |
+----+--------+--------+我尝试了两次查询,第一次返回所有有module=5的课程,第二次返回所有有模块!=5的课程,然后保存2个文件并执行unix命令diff来查看两个文件之间的差异。
但我想返回所有的课程,其中只有module=5在一个查询。有可能吗?
发布于 2016-06-17 14:59:29
为了让它变得简单,让我们只需要解决mdl_course_modules
SELECT course
FROM mdl_course_modules
GROUP BY course
HAVING SUM(module <> 5) = 0
AND SUM(module = 5) = 1 -- or >= 1发布于 2016-06-17 14:58:12
这样做的一种方法是使用带关联子查询的现有谓词。
select *
from mdl_course_modules t
where not exists (
select 1
from mdl_course_modules
where t.course = course -- reference the outer table
and module <> 5 -- and find rows that have any other module than 5
) 由于还不完全清楚哪些数据在哪个表中,因此您必须调整表名和列名以适应您的设置,但概念应该是明确的。
发布于 2016-06-17 15:03:15
您可以使用not in子查询来执行以下操作:
SELECT DISTINCT fullname
FROM mdl_course
LEFT JOIN mdl_course_modules
ON mdl_course.id=mdl_course_modules.course
WHERE mdl_course_modules.module=5
AND course.id not in (SELECT course
FROM mdl_course_modules
WHERE module <> 5)https://stackoverflow.com/questions/37884574
复制相似问题