连接查询以获取与一列中的2个值匹配的记录

时间:2018-12-16 16:25:22

标签: mysql sql

所以,我有一个电影表(电影),一个类别表(猫)和它们的关系表(movie_cat)。
“电影”表的值为

id  label     
1   Ironman   

“ cat”表具有值

id  label      value
1   Genre      Action
2   Language   English

“ movie_cat”表具有值

id  movie_id  cat_id
1     1           1
2     1           2
  

我需要一个查询,该查询可以为我提供“动作”和“英语”类别的电影列表。

1 个答案:

答案 0 :(得分:0)

直接的方法:

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
);