首页 > 解决方案 > 加入查询以获取匹配一列中 2 个值的记录

问题描述

所以,我有一个电影表(movie)、一个类别表(cat)和它们的关系表(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

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

标签: mysqlsql

解决方案


直截了当的方法:

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

推荐阅读