简体   繁体   English

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

[英]Join query to get records matching 2 values in one column

So, I have a movie table (movie), a category table (cat), and their relation table (movie_cat). 因此,我有一个电影表(电影),一个类别表(猫)及其关系表(movie_cat)。
The "movie" table has values “电影”表具有值

id  label     
1   Ironman   

The "cat" table has values “猫”表具有值

id  label      value
1   Genre      Action
2   Language   English

The "movie_cat" table has values “ movie_cat”表具有值

id  movie_id  cat_id
1     1           1
2     1           2

I need a query that can give me the list of movies which are in "Action" and "English" category. 我需要一个查询,该查询可以为我提供“动作”和“英语”类别中的电影列表。

The straight-forward approach: 简单的方法:

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

The aggregation approach: 汇总方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM