2016-11-15 125 views
0

我有两个表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 

我需要编写一个查询来选择谁参加了在这两个数学巨星&英语巨星的学生。

我用这个查询

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

,但它给谁参加数学巨星或英文巨星结果的学生。 请帮我

回答

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 
+0

这是好的,但如果更多的类别,然后几乎不可能,我需要动态生成此查询。 – Shameem

+1

@jan一些修正:SELECT student_name FROM学生甲 INNER JOIN student_category乙ON A.id = B.student_id AND B.category_id IN(1,4) GROUP BY student_name HAVING COUNT(*)= 2 – Shashikala

+0

@Webbie,第二个SQL是根据Shameem所述的扩展请求 – Jan

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

例检查谁参加了所有类别或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; 

希望它能帮助。

+0

一组通过,如果你使用HAVING子句 – Jan

+0

不知道如何可能会更干净“GROUP BY”会适合在这里? –

+0

这不起作用 – Shameem