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

标签 mysql sql

所以,我有一个电影表(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

I need a query that can give me the list of movies which are in "Action" and "English" category.

最佳答案

直接的方法:

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

关于mysql - 连接查询以获取与一列中的 2 个值匹配的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53804135/

相关文章:

mysql - 查询限制不起作用

sql - select @@identity 是做什么的?

php - 使用不同数据类型的许多值构建插入语句

php - 使用 Eloquent 选择具有值的最后一条记录

mysql - 使用mysql计算每天的工作时间

sql - T-Sql算法问题

mysql - 使用 MAX 函数时返回多条记录?

sql - MySQL 查询语法帮助

php - Eloquent 查询 - 多列上的 COUNT 和 SUM

mysql - 长时间响应, float 错误