我想写一个查询,显示连续两年发表论文的作者的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是作者的外键,Authored.pid是纸张的外键。到目前为止,这是我所得到的,但这并没有给我想要的结果,我也不知道出了什么问题:
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;发布于 2020-05-05 02:52:34
您需要GROUP BY au1.aid才能获得不同的作者:
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 AND p1.year+1 = p2.year
GROUP BY au1.aid
ORDER BY au1.aid发布于 2020-05-05 01:57:06
不确定您的查询,但是IN子句看起来很有用:
where paper.year IN ('2019', '2020') https://stackoverflow.com/questions/61604421
复制相似问题