使用过滤器进行多对多查询

时间:2011-10-01 10:58:37

标签: mysql many-to-many

我有以下问题。有两个表 - groupsstudents以及第三个数据透视表group_student

查询来自特定群体(身份:1,8)的学生是明确的......

   SELECT DISTINCT s.*
   FROM students AS s
   Inner Join group_student AS gs ON gs.student_id = s.id
   Inner Join groups AS g ON g.id = gs.group_id
   WHERE g.id IN ("1","8")

有效。但是,如果我想只选择组ID为1的学生段,如何查询。例如s.name = "john"。所以结果应该是:all students from group id 8 + all students with name "john" from group id 1

Thanx帖子: - )

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT DISTINCT s.*
   FROM students AS s
   Inner Join group_student AS gs ON gs.student_id = s.id
   Inner Join groups AS g ON g.id = gs.group_id
   WHERE g.id ="8" or (g.id="1" and s.name = "john")

答案 1 :(得分:1)

你也可以使用UNION

SELECT DISTINCT s.*
   FROM students AS s
   Inner Join group_student AS gs ON gs.student_id = s.id
   Inner Join groups AS g ON g.id = gs.group_id
   WHERE g.id = 8
UNION
SELECT DISTINCT s.*
   FROM students AS s
   Inner Join group_student AS gs ON gs.student_id = s.id
   Inner Join groups AS g ON g.id = gs.group_id
   WHERE gp.id="1" and s.name = "john"

答案 2 :(得分:0)

还有一个选项,即避免DISTINCT和(可能不需要)加入groups

SELECT s.*
FROM students AS s
WHERE EXISTS
        ( SELECT *
          FROM group_student AS gs 
          WHERE gs.student_id = s.id
            AND (  gs.group_id = 8
                OR (gs.group_id, s.name) = (1, 'john')
                )
        )