mysql - 加入查询以获取匹配一列中 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
我需要一个可以给我“动作”和“英语”类别的电影列表的查询。
解决方案
直截了当的方法:
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
);
推荐阅读
- android - 将特定活动保持在后台堆栈之上
- python - 带有 TikZ 风格路径装饰的 Matplotlib 注释箭头
- scala - “产品”是否意味着“反射”?
- r - 是否可以对整个 JupyterLab Notebook 进行基准测试?
- debugging - 如何从 IDE 运行/调试流式应用程序
- html - 一个元素中的几个名称类
- php - 在 PHP 库中传递/使用调试类的最佳方法
- c# - 为什么 C# finally 块会导致额外的方法调用?
- c# - 将 PictureBox 链接到类中的对象
- kubernetes - Flink 应用程序接收器 KafkaProducer 抛出 java 堆空间错误(内存不足)