使用以下架构:
create table awards(
aid int primary key
, name varchar(100) not null );
create table institutions(
iid int primary key
, name varchar(100) not null );
create table winners(
aid int
, iid int
, year int
, filmname varchar(100)
, personname varchar(100)
, primary key (aid, iid, year)
, foreign key tid references awards(aid)
, foreign key cid references institutions(iid) );
我创建了以下查询:
SELECT nominees.personname as personname, awards.name as award, nominees.year as year
FROM nominees, institutions, awards WHERE institutions.iid = nominees.iid and
awards.aid = nominees.aid and personname is not null
GROUP BY nominees.personname, awards.name, nominees.year
HAVING ((awards.name, count(DISTINCT institutions.name)) in
(SELECT awards.name as
awards, count(DISTINCT institutions.name)
FROM nominees, awards, institutions
WHERE nominees.aid = awards.aid and nominees.iid = institutions.iid
GROUP BY awards.name))
ORDER BY nominees.personname, awards.name;
此查询旨在查找在特定年份授予该奖项的每个机构都提名了一个人的所有奖项。它本质上需要一个人并计算授予他们单个奖项的机构数量,并将该值与授予该奖项的最大机构数量进行比较。
所需的输出应如下所示:
"personname" "award" "year"
"Alexandre" "score" "2011"
"Skyfall" "song" "2013"
"Tangled" "song" "2011"
这给出了我想要的集合,但是我不确定以不同的方式做它是否更有效。我试图让它与 EXISTS 一起工作,但我没有太多运气。
主要问题:有没有更有效的方法来做这个查询?