我不知道如何在标题中解释这个问题所以我会给你一个电影和演员的例子。
我有三个表(表名 - 字段):
actor - id, name
movie - id, title
actor_movie - actor_id, movie_id
我想创建一个在WHERE子句中使用actor.id的查询,输出应该是使用此actor处理电影的actor列表。最好按照他们一起合作过多少部电影来排序。
编辑:这是我现在得到的,但它没有显示其他演员。它只计算演员157的电影数量:
SELECT a.name, COUNT(m.title) movie_count
FROM actor_movie
JOIN actor
ON actor.id = actor_movie.actor_id
WHERE actor.id = 157
GROUP BY actor.name
ORDER BY movie_count DESC
答案 0 :(得分:1)
使用演员选择电影,选择电影中的其他演员,按演员和计数分组。
select a.id, a.name, count(*)
from actor a
join actor_movie am on am.actor_id = a.id
where movie_id in (select movie_id from actor_movie where actor_id = @actor)
and actor_id <> @actor -- remove this if you want to see how many movies the @actor has
group by a.id
order by count(*) desc;
另一种写这个的方法:
select a.id, a.name, counted.movies
from actor a
join
(
select actor_id, count(*) as movies
from actor_movie
where movie_id in (select movie_id from actor_movie where actor_id = @actor)
and actor_id <> @actor -- remove this if you want to see how many movies the @actor has
group by actor_id
) counted on counted.actor_id = a.id
order by count(*) desc;
而另一个:
select
actor_id,
(select name from actor a where a.id = am.actor_id) as name,
count(*) as movies
from actor_movie am
where movie_id in (select movie_id from actor_movie where actor_id = @actor)
and actor_id <> @actor -- remove this if you want to see how many movies the @actor has
group by actor_id
order by count(*) desc;