SQL索引搜索

时间:2012-03-07 12:02:50

标签: sql indexing database

对于这项任务,我应该找到参与50多部电影的演员的所有名字。对于每一部电影,我都必须检查他们的姓氏是否与电影中的其他演员一起出现在alphabeth中。

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);

关于某些电影类型的一些解释=>

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

我如何实际检查这个人是否先出现在alphabeth和其他演员之间?

示例=>电影纸浆小说......(还有其他一些演员,但主要的角色) Samuel L. Jackson ||约翰特拉沃尔塔(John Travolta)很容易看到杰克逊在特拉沃尔塔(Travolta)之前出现,所以詹姆斯等人数为+1 ......

我看过一个看似min的伪代码(该影片中的p.lastname)或p.lastname< = all(电影中的p.lastname)

我怎样才能使用它们中的任何一个?或者这是一种更好的方式吗?

1 个答案:

答案 0 :(得分: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;