最常见的SQL

时间:2019-01-11 17:38:48

标签: sql postgresql

我想找出哪些演员主要在喜剧电影中表演。 他们的大多数电影作品都是喜剧。

因此,当演员有7部电影,其中4部是喜剧电影时。

(还有所有只演过喜剧的演员。)

表“演员”:

|id_actor| name |
|--------|------|
|  12    |franco|
|  13    |rogen |
|  14    |hill  |
|  15    |teller|
|  16    |john  |

表格“类型”

|id_genre|    name    |
|--------|------------|
|  22    |comedy      |
|  23    |thriller    |
|  24    |documentary |

表“ plays_in”:

|id_actor|    id_film |
|--------|------------|
|  12    |      5001  |
|  12    |      5002  |
|  12    |      5003  |
|  13    |      5004  |
|  13    |      5005  |
|  13    |      5006  |
|  14    |      5007  |
|  14    |      5008  |

表is_in_genre

|id_genre|    id_film |
|--------|------------|
|  22    |      5001  |
|  22    |      5002  |
|  22    |      5003  |
|  23    |      5004  |
|  23    |      5005  |
|  24    |      5006  |
|  24    |      5007  |
|  24    |      5008  |

这就是我所拥有的,但没有显示演员,只演喜剧。

select      id_actor, name 
from        actor x where
(
    select      count(id_film) 
    from        actor y
    natural join plays_in 
    natural join movie
    natural join is_in_genre
    where       id_genre = 4001 and x.id_actor = y.id_actor 
    group by    id_actor
)
<=
(
    select      count(id_film) 
    from        actor y
    natural join plays_in 
    natural join movie
    natural join is_in_genre
    where       id_genre != 4001 and x.id_actor = y.id_actor 
    group by    id_actor
)

2 个答案:

答案 0 :(得分:0)

加入所有4个表并按演员分组。
为了只获得喜剧率超过50%的演员,分组后的条件是:
having (1.0 * sum(case when genrename = 'comedy' then 1 else 0 end ) / count(genrename)) > 0.5

select 
  t.actorname
from (
select 
  actor.name actorname, genre.name genrename
from actor 
inner join plays_in
on plays_in.id_actor = actor.id_actor
inner join is_in_genre
on is_in_genre.id_film = plays_in.id_film
inner join genre
on genre.id_genre = is_in_genre.id_genre
) t
group by t.actorname
having (1.0 * sum(case when genrename = 'comedy' then 1 else 0 end ) / count(genrename)) > 0.5

请参见demo

答案 1 :(得分:0)

当一部电影是喜剧片时,它就是一部喜剧片。您要寻找的演员主要是喜剧电影。

with comedies as
(
  select id_film
  from is_in_genre
  group by id_film
  having count(case when id_genre = (select id_genre from genre where name = 'comedy') then 1 end) > 0
)
, comedy_actors as 
(
  select id_actor
  from plays_in
  group by id_actor
  having avg(case when id_film in (select id_film from comedies) then 1 else 0 end) > 0.5
)
select *
from actor
where id_actor in (select id_actor from comedy_actors);