2016-11-15 77 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