2012-03-07 155 views
0

對於這個任務,我應該找到所有參與超過50部電影的演員的名字。對於每部電影,我都要檢查他們的姓是否與電影中的其他演員排在首位。SQL索引搜索

select 
    lastname, firstname, count(*) as films 
from 
    (select 
      distinct p.lastname, p.firstname, f.filmid 
     from 
      person p, filmparticipation f, filmitem i, film fi 
     where 
      fi.filmid = i.filmid and 
      i.filmid = f.filmid and 
      p.personid = f.personid and 
      f.parttype = 'cast' and filmtype = 'C') person 
group by 
    lastname, firstname 
having 
    count(*) >= 450 
order by 
    lastname, firstname desc; 

下面是關於查詢的一些相關表格

create table person(
personid int primary key, 
lastname text not null, 
firstname text not null, 
gender(1), 
); 
create index personlastnameindex on person (lastname); 

create table filmparticipation (
partid int primary key, 
personid int not null references person (personid), 
filmid int not null references filmitem (filmid), 
parttype text not null 
); 

create index filmparticipationpersonidindex on filmparticipation (personid); 
create index filmparticipationpersonidindex on filmparticipation (filmid); 

create table film(
filmid int primary key references filmitem (filmid), 
title text not null, 
prodyear int 
); 

create index filmtitleindex on film (title); 
create index filmyearindex on film (prodyear); 

對於一些filmtypes一些explainasions =>

C => cinema movie V => videomovie VG => videogame TV => TV-film..... 

實際上,我怎麼讓檢查人員首先來了在alphabeth與其他演員?

例子=>電影紙漿小說...(有幾個其他演員,但採取主要字符) Samuel L. Jackson ||約翰特拉沃爾塔很容易看到,傑克遜在Travolta之前,所以+1計數爲傑克遜等...

我見過一個僞代碼,看起來像min(p.lastname在那部電影)或p。姓氏< =全部(電影中的p.lastname)

我該如何使用它們中的任何一個?還是更好的方法?

+0

什麼用'filmitem'表的?看不到該表的創建。 – 2012-03-07 12:16:40

+0

所以你只想計算列表中第一位的演員(當電影的演員名單是按他們的姓氏排序的)? – Eggi 2012-03-07 12:22:57

+0

電影有一個演員表。考慮到該電影的演員名單,我試圖從該列表中獲取min(p.lastname)並以某種方式計算它 – CptHindsight 2012-03-07 12:43:51

回答

0

假設你正在使用包括ROW_NUMBER()在一個RDBMS,請嘗試:

select lastname, 
     firstname, 
     count(distinct filmid) as films, 
     count(distinct case when rn=1 then filmid end) as alpha_first 
from 
(select p.lastname, 
     p.firstname, 
     f.filmid, 
     row_number() over (partition by f.filmid order by lastname, firstname) rn 
from person p, filmparticipation f, filmitem i, film fi 
where fi.filmid = i.filmid and 
     i.filmid = f.filmid and 
     p.personid = f.personid and 
     f.parttype = 'cast' and filmtype = 'C') person 
group by lastname, firstname 
having count(distinct filmid) >= 50 
order by lastname, firstname desc;