WHERE子句中的操作和OR

时间:2014-03-07 14:15:53

标签: mysql sql

我遇到了获取数据的问题。我想找到所有包含指定标志的课程。如何编写SQL代码来查找标记相同类型的课程是OR条件,而其他类型是在AND条件之间。

课程表的记录:

+----+----------+
| id |   name   |
+----+----------+
| 1  |  Spring  |
| 2  | Hibernate|
| 3  |  LATEX   |
+----+----------+

course_flags 表的记录:

+----+----------+----------+
| id |course_id |  flag_id |
+----+----------+----------+
| 1  |     1    |     1    |
| 2  |     1    |     2    |
| 3  |     1    |     3    |
| 4  |     2    |     2    |
| 5  |     2    |     3    |
+----+----------+----------+

标志表的记录:

+----+-------------+-------------+
| id |     name    |     type    |
+----+-------------+-------------+
| 1  |  promotion  |   NORMAL    |
| 2  | last minute |   NORMAL    |
| 3  |   Samsung   |ACCREDITATION|
| 4  |    Nokia    |ACCREDITATION|
+----+-------------+-------------+

我的查询

 SELECT course.id,
      course.course_name,
      GROUP_CONCAT(Flags.id SEPARATOR ',') as flags
 FROM course
 INNER JOIN course_flags ON 
    course.id = course_flags.course_id
 INNER JOIN flags ON 
    flags.id = course_flags.flags_id
 AND ((flags.id =1 OR flags.id =2) AND flags.id = 3)
 GROUP BY course.id, course.course_name

不幸的是,我的数据库引擎返回了零记录。

我原本希望得到这个结果:

+----+----------+----------+
| id |   name   |   flags  |
+----+----------+----------+
| 1  | Spring   |  1,2,3   |
| 2  | Hibernate|   2,3    |
+----+----------+----------+

问我怎么得到它?

提前致谢!

1 个答案:

答案 0 :(得分:3)

正如your previous question已经回答的那样,JOIN谓词(与WHERE子句一样)将记录之前的限制为分组;而HAVING子句在分组后限制结果

SELECT   course.id, course.name, GROUP_CONCAT(flags.id) flags
FROM     course
    JOIN course_flags ON course_flags.course_id = course.id
    JOIN flags ON flags.id = course_flags.flag_id
GROUP BY course.id
HAVING   SUM(flags.id IN (1,2)) AND SUM(flags.id = 3)

sqlfiddle上查看。