帮助(有点简单)MySQL JOIN

时间:2011-01-23 06:25:34

标签: mysql

考虑我有三张桌子:

  • 电影(电影1,电影2等)
  • 类别(动作,悬疑等)
  • Movies_Categories(电影1 - >动作,电影1 - >悬疑,电影2 - >悬疑等)

如何仅使用1个查询选择仅属于或不属于特定类别的电影?

谢谢!

2 个答案:

答案 0 :(得分:1)

所属:

    SELECT m.*
      FROM movies m
INNER JOIN movies_categories mc
        ON m.id = mc.movie_id
INNER JOIN categories c
        ON c.id = mc.category_id
       AND c.name = 'action';

不属于:

         SELECT m.*
           FROM movies m
LEFT OUTER JOIN (SELECT mc.movie_id
                   FROM movies_categories mc
             INNER JOIN categories c
                     ON c.id = mc.category_id
                    AND c.name = 'action') mcx
             ON m.id = mcx.movie_id
          WHERE mcx.movie_id IS NULL

答案 1 :(得分:0)

    SELECT m.*,
           IF(mc.movie_id IS NULL, 'doesnt belong', 'belongs')
      FROM Movies m
 LEFT JOIN Movies_Categories mc ON mc.movie_id = m.id
                               AND mc.category_id = (SELECT id
                                                       FROM categories
                                                      WHERE name = 'action')