使用INNER JOIN,GROUP BY和LIMIT进行选择

时间:2016-12-08 20:10:07

标签: mysql

我有三张关于电影的表格。第一个是movie,第二个是actor,最后一个是movie_actor_mapping。我写了一个查询,从每个电影的表电影和组演员中选择数据。我的查询从actor表中选择所有演员,但我必须只选择前4个演员。如何修改我的选择呢?

SELECT title, year, poster, rating, group_concat(a.name separator ', ') as actors
FROM movie m
INNER JOIN movie_actor_mapping ma ON m.movie_id = ma.movie_id
INNER JOIN actor a ON a.actor_id = ma.actor_id
WHERE m.rating IS NOT NULL
GROUP BY m.movie_id
ORDER BY m.rating DESC;

1 个答案:

答案 0 :(得分:1)

你可以通过substringing group_concat输出来破解前三个结果,例如:

select m.name as movie, substring_index(group_concat(a.name SEPARATOR ','), ',', 3) as actors
from movie m
join movie_actor ma on m.id = ma.movie_id
join actor a on ma.actor_id = a.id
group by m.id
order by m.id, a.id;

这会为每部电影提供3个演员。

这是SQL Fiddle