join查询在一列中获得与2个值匹配的记录

btxsgosb  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(247)

所以,我有一个movie表(movie)、一个category表(cat)和它们的关系表(movie\u cat)。
“movie”表具有值

id  label     
1   Ironman

“cat”表有值

id  label      value
1   Genre      Action
2   Language   English

“movie\u cat”表有值

id  movie_id  cat_id
1     1           1
2     1           2

我需要一个查询,可以给我的电影在“行动”和“英语”类别的名单。

y4ekin9u

y4ekin9u1#

直截了当的方法:

select *
from movie
where id in 
  (select movie_id from movie_cat where cat_id = 
    (select id from cat where label = 'Genre' and value = 'Action'))
and id in
  (select movie_id from movie_cat where cat_id =
    (select id from cat where label = 'Language' and value = 'English'));

聚合方法:

select *
from movie
where id in 
(
  select movie_id
  from movie_cat 
  where cat_id in (select id from cat where (label, value) in (('Genre', 'Action'),
                                                               ('Language', 'English'))
  group by movie_id
  having count(*) = 2
);

相关问题