Mysql IN查询而不是多个AND条件


Mysql IN query instead of multiple AND conditon

我有三个mysql表,类别,学生和学生类别。对于每个学生,将有一个或多个类别,并将其存储在student_category中,如下所示。

1)   Categgory
   ----------------------------
    id      |  category_name
   ---------------------------
    1       |   A
    2       |   B
    3       |   C
    4       |   D

2)   Students
--------------------------
  id    |   name   
--------------------------
  1     | John
  2     | Kumar
  3     | Ashok
  4     | Jorge
  5     | Suku
 -------------------------

2)  student_category
  -----------------------------------------
    id    |   student_id    |  category_id
   -----------------------------------------
    1     |     1           |    2
    2     |     1           |    4
    3     |     2           |    3
    4     |     2           |    1
    5     |     3           |    2
 ------------------------------------------ 

我需要选择包含category_id 2和4的学生

我使用了如下查询,但它返回的学生要么包含类别2,要么包含类别4。

   select A.name from students A, student_category B where A.id=B.student_id
   and B.category_id IN (2,4) 

试试这个查询:

SELECT t1.id,
       t3.name
FROM students t1
INNER JOIN student_category t2
    ON t1.id = t2.student_id
INNER JOIN students t3
    ON t1.id = t3.id
WHERE t2.category_id IN (2, 4)
GROUP BY t1.id
HAVING COUNT(DISTINCT t2.category_id) = 2

解释:

这个查询将studentsstudent_category表连接在一起,然后删除所有不是类别2或4的记录。这意味着每个学生只有第2类和第4类记录与他相关联。然后HAVING子句进一步限制,要求学生有两个不同的类别,如果为真,则必须意味着该学生同时具有类别2和类别4。

演示:

SQLFiddle

try this:

select name from Students where id in (select student_id from student_category where category_id in (2,4))

试试这个:

select 
    s.name
from
    Students s,
    Categgory c,
    student_category sc
where
    sc.student_id = s.id
        and sc.category_id = c.id
        and c.id = 2
        and c.id = 4

你可以在SQL Fiddle上查看。必须取distinct学生名,因为如果一个学生属于多个类别,它会重复。