Я хочу написать запрос, который отображает ID автора, опубликовавшего статьи в течение двух лет подряд. Вот схема базы данных:
CREATE TABLE Author (aid integer NOT NULL,
name varchar(50) NOT NULL,
affiliation varchar(50), primary key(aid));
CREATE TABLE Paper (pid integer NOT NULL,
title varchar(50) NOT NULL,
year integer NOT NULL, primary key(pid));
CREATE TABLE Authored (aid integer references Author,
pid integer references Paper,
primary key(aid, pid), foreign key(aid) references Author(aid), foreign key(pid) references Paper(pid));
insert into Author(aid, name, affiliation) values (1, "A", "DS");
insert into Author(aid, name, affiliation) values (2, "B", "PS");
insert into Author(aid, name, affiliation) values (3, "C", "CS");
insert into Paper(pid, title, year) values (100, "DS1", 2019);
insert into Paper(pid, title, year) values (101, "PS1", 2019);
insert into Paper(pid, title, year) values (102, "CS1", 2019);
insert into Paper(pid, title, year) values (103, "DS2", 2020);
insert into Paper(pid, title, year) values (104, "PS2", 2020);
insert into Paper(pid, title, year) values (105, "CS2", 2019);
Authored.aid - это внешний ключ для Author, а Authored.pid - это внешний ключ для Paper. И это то, что у меня есть до сих пор, но это не дает мне желаемого результата, и я не знаю, что не так:
select au1.aid, a1.name
from authored au1 inner join authored au2 on au1.aid=au2.aid
inner join author a1 on au1.aid=a1.aid
inner join paper p1 on au1.pid=p1.pid
inner join paper p2 on au2.pid=p2.pid
where p1.year = p2.year+1
order by au1.aid;