MYSQL多选同一类别?

时间:2009-09-14 17:05:46

标签: sql mysql

我有3个表(场景,类别,scenes_categories),多对多关系。

场景(id,title,description) 类别(标识,标题) 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匹配的记录?

2 个答案:

答案 0 :(得分:4)

对于您要求的每个categoryId,您需要要求该sceneId的多对多表中存在一行: 所以试试这个:

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'

答案 1 :(得分:2)

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