2017-05-24 69 views
-1

我不知道如何在標題中解釋這個問題,所以我會給你一個電影和演員的例子。MySQL - 查找演員一起工作過的其他演員

我有三個表(表名 - 字段):

actor - id, name 
movie - id, title 
actor_movie - actor_id, movie_id 

我想創造的是,在使用一個actor.id查詢的WHERE子句和輸出應該是誰的工作角色名單與這位演員合演電影。最好根據他們一起工作多少部電影來訂購。

編輯:這是我現在得到的,但它不顯示其他演員。它只能算演員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

出了什麼問題?你有沒有嘗試過任何東西? –

+0

說實話,我不確定從哪裏開始,而不是非常基本的SELECT。您的評論表明有一個簡單的解決方案。 :) – Kaah

+0

開始學習。你需要'JOIN','COUNT','GROUP BY' –

回答

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; 
+0

非常感謝。我認爲我需要一個子查詢,但我沒有在WHERE子句中使用它。 'actor_id <> @演員'是一個非常好的接觸! 對於如何將問題標題更改爲描述性,您有什麼建議嗎? – Kaah

+0

不客氣。該標題完美適合您的問題。不要改變它。 –