Посчитать количество строк с условиям из другой таблицы
Помогите пожалуйста.
Есть таблица с Актерами (name), с фильмами (title), и с информацией о том в каком фильме какой актер играл (cast_info).
Мне нужно посчитать в скольких фильмах снялся актер. Я пишу
select count(1)
FROM from cast_info
where person_id=(select id from name where name like ('Depp, Johnny'))
нахожу все фильмы и сериалы где он снимался.
А в таблице titleесть столбец kind_id которая указывает на то что это — фильм, сериал, тв шоу и т.п.
Я хочу поставить условие что бы считались только фильмы, не сериалы и прочее. Это kind_id=1.
Я по разному пробовал, но последнее вот
select count(1)
FROM (
select
from cast_info c, title t
where person_id=(select id from name where name like ('Depp, Johnny'))
and t.kind_id=1
) AS pss
Но считает все строки 565 470 048.
Как поставить условие?
Ответы (3 шт):
Автор решения: Tuti
→ Ссылка
select count(1)
FROM
(select
from cast_info c, title t
where person_id=(select id from name where name like ('Depp, Johnny'))
and c.movie_id = t.id
and t.kind_id=1) AS pss
Автор решения: HeathRow
→ Ссылка
Связи между таблицами не прописаны, но если без вложенных запросов, то примерно будет так:
create table actors(
actor_id integer,
name text
)
create table titles(
title_id integer,
name text,
kind_id integer
)
create table cast_info(
actor_id integer,
title_id integer
)
insert into actors select 1, 'actor1'
insert into actors select 2, 'actor2'
insert into actors select 3, 'actor3'
insert into titles select 1, 'title1', 1
insert into titles select 2, 'title2', 1
insert into titles select 3, 'title3', 1
insert into titles select 4, 'title4', 2
insert into cast_info select 1, 1
insert into cast_info select 1, 2
insert into cast_info select 1, 4
insert into cast_info select 2, 1
insert into cast_info select 2, 2
select
a.actor_id,
a.name,
count(t.*)
from
actors a
left join
cast_info c
on
c.actor_id = a.actor_id
left join
titles t
on
t.title_id = c.title_id
where
a.name like ('actor1') and
t.kind_id = 1
group by
a.actor_id,
a.name
Автор решения: santavital
→ Ссылка
SELECT name.name, count(cast_info.*)
FROM name
LEFT JOIN cast_info ON name.id = cast_info.АктёрИД
WHERE name.name like ('Depp, Johnny')
GROUP BY name.name