2009-09-14 101 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是动态的,这可能会更容易实现。