2009-09-14 131 views
0

我有3個表(場景,類別,scenes_categories)在多對多的關係。MYSQL多個選擇相同的類別?

場景(ID,標題,描述) 類別(ID,標題) scenes_categories(scene_id,CATEGORY_ID)

我有問題,查詢數據以選擇必須多個類別相匹配的場景。例如,我可能想要選擇與類別3和類別5以及類別8匹配的場景,但我無法弄清楚如何使其發揮作用。

到目前爲止,我已經得到的東西像

SELECT scenes.id, scenes.title, scenes.description 
FROM scenes 
LEFT JOIN scenes_categories ON scenes.id = scenes_categories.scene_id 
LEFT JOIN categories ON scenes_categories.category_id = categories.id 
WHERE scenes_categories.category_id = '3' 
AND scenes_categories.category_id = '5' 
AND scenes_categories.category_id = '8' 
AND scenes.id = '1' 

我如何選擇必須匹配記錄了所有類別ID的規定?

回答

4

你需要需要一個行中的許多一對多表存在該sceneId,每個CATEGORYID你需要: 那麼試試這個:

SELECT s.id, s.title, s.description 
FROM scenes s 
WHERE s.id = '1' 
    And Exists (Select * From scenes_categories 
       Where scene_id = s.Id 
        And category_id = '3') 
    And Exists (Select * From scenes_categories 
       Where scene_id = s.Id 
        And category_id = '5') 

    And Exists (Select * From scenes_categories 
       Where scene_id = s.Id 
        And category_id = '8') 

應該工作是另一種選擇做三內連接,而不是:

SELECT s.id, s.title, s.description 
FROM scenes s 
    Join scenes_categories c3 
     On c3.scene_id = s.Id 
      And c3.category_id ='3' 
    Join scenes_categories c5 
     On c5.scene_id = s.Id 
      And c5.category_id ='5' 
    Join scenes_categories c8 
     On c8.scene_id = s.Id 
      And c8.category_id ='8'  
WHERE s.id = '1' 
+0

很確定他在找這裏的動態解決方案。 – Zoidberg 2009-09-14 17:15:49

+0

對不起,我脫下了我的downvote ...沒有意識到他不想要一個OR關係 – Zoidberg 2009-09-14 17:19:43

+0

@zoid,np,thx第二次看! – 2009-09-14 17:23:27

2

查爾斯BRETANA的答案將工作,但可能要檢查其性能反對這個,看看哪個適合你更好。

SELECT * FROM scenes 
INNER JOIN (
    SELECT scene_id 
    FROM scenes_categories 
    WHERE category_id IN (3,5,8) 
    GROUP BY scene_id 
    HAVING count(*) = 3 
) valid ON scenes.id = valid.scene_id 

假設你的SQL是動態的,這可能會更容易實現。