具有多个条件的MySql查询

时间:2016-11-15 08:50:52

标签: php mysql

我有两张桌子

1) Student

 id   |   Student_name
--------------------
 1    |   John
 2    |   Joy
 3    |   Raju

2) Category

 id    |  category_name
-------------------------
 1     |  Maths Fest
 2     |  Science Fest
 3     |  IT Fest
 4     |  English Fest
 5     |  Cultural Fest

3) Student_category

  id   | student_id  | category_id
 ------------------------------------
  1    |    1        |     4
  2    |    1        |     5
  3    |    1        |     1
  4    |    2        |     1
  5    |    2        |     4
  6    |    3        |     1
  7    |    3        |     5
  8    |    3        |     3

我需要写一个查询来选择参加过Maths fest&英语节日。

我使用了这个查询

SELECT distinct student_name 
FROM student A,student_category B 
WHERE A.id=B.student_id 
  and B.category_id IN ('1','4')

但它给参加数学节或英语节的结果学生。 请帮帮我

2 个答案:

答案 0 :(得分:1)

如果您必须有两个不同的类别,则只需加入两次:

SELECT student_name 
FROM student A
  INNER JOIN student_category B ON A.id=B.student_id AND B.category_id = 1
  INNER JOIN student_category C ON A.id=C.student_id AND C.category_id = 4

通过这种方式,您可以获得两个连接都存在的学生

对于动态选择类别(超过2,如果您知道金额和连接表不包含重复项),您可以这样做

SELECT student_name
  FROM student A 
    INNER JOIN student_category B on A.id = B.student_id 
        AND B.category IN (1,4,5) -- one more
  GROUP BY student_name 
  HAVING count(*) = 3 -- Number of categories in IN clause

答案 1 :(得分:0)

试试这个:

SELECT student_name
  FROM student A 
 INNER JOIN student_category B 
       ON A.id = B.student_id AND B.category_id IN ( 1, 4 ) 
 GROUP BY student_name HAVING count( * ) = 2  

此查询仅在该学生姓名的计数为两次时返回学生姓名。一次是英语节,一次是数学节。

如果有更多类别,那么您只需计算逗号分隔字符串中有多少个类别,并将count(*) = 2替换为count(*) = no. of categories

检查参与所有类别或超过2类别的学生的示例:

$category_id = 1, 2, 3, 4, 5  
$a = substr_count($category_id, ","); // this will count number of times comma is appearing in your string.
$a = $a + 1;                         // number of items is + 1 than number of commas.  

查询如下所示:

SELECT A.student_name 
  FROM student A,
       student_category B   
 WHERE A.id = B.student_id AND B.category_id IN ('1', '4')  
HAVING count(*) = $a;  

希望它有所帮助。