这只是一个大学练习,所以我并不着急。但我想已经知道答案了。考虑这些表和行:
create table course (
numco integer,
nameco varchar(20) not null,
primary key (numco)
);
create table prereq (
numco integer,
numcoprereq integer,
primary key (numco, numcoprereq),
foreign key (numco) references course (numco),
foreign key (numcoprereq) references course (numco)
);
insert into course values (1, 'course 1');
insert into course values (2, 'course 2');
insert into course values (3, 'course 3');
insert into course values (4, 'course 4');
insert into course values (1, 'course 5');
insert into course values (2, 'course 6');
insert into prereq values (4, 2);
insert into prereq values (2, 1);
我没有做这个。我只是翻译了它并删除了一些不相关的部分。我知道有两course
排PK相同,但这一排我得问我的老师。
他让我们写一个查询来获取课程名称和课程先决条件的名称。如果它只是课程的编号,左连接就可以了。但我不能让它与名字一起工作。它应该输出:
course 1 (null)
course 2 course 1
course 3 (null)
course 4 course 2
course 5 (null)
course 6 course 1
我搜索了很多并写了两次尝试:
select C1.nameco, C2.nameco as namecoprereq
from course C2 left join
(course C1 join prereq P on C1.numco = P.numco)
on C2.numco = P.numcoprereq;
select C1.nameco, C2.nameco as namecoprereq
from (course C1 join prereq P on C1.numco = P.numco)
left join course C2 on C2.numco = P.numcoprereq;
它们分别输出:
course 2 course 1
course 6 course 1
course 4 course 2
(null) course 3
(null) course 4
course 2 course 5
course 6 course 5
course 4 course 6
和
course 2 course 1
course 2 course 5
course 4 course 2
course 4 course 6
course 6 course 1
course 6 course 5
我知道(我想,我没有尝试过)我可以用联合和减号来做到这一点,但我想知道是否可以在一次选择中做到这一点。关于如何做到这一点的任何想法?