繁体   English   中英

具有多个条件的MySQL查询

[英]MySql Query with multiple condition

我有两张桌子

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

我需要写一个查询来选择同时参加数学节和英语节的学生。

我用这个查询

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

但是它给参加数学节或英语节的成绩学生。 请帮我

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

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

尝试这个:

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 count(*) = no. of categories

检查参与所有类别或两个类别以上的学生的示例:

$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;  

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM