gpt4 book ai didi

MySQL:如何进行涉及连接和左连接的查询

转载 作者:行者123 更新时间:2023-11-29 03:07:08 25 4
gpt4 key购买 nike

这只是一次大学练习,所以我并不着急。但我想知道答案了。考虑这些表和行:

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,但我必须就此询问我的老师。

他要求我们编写查询以获取类(class)名称和类(class)先决条件的名称。如果它只是类(class)的编号,左连接就可以了。但我不能让它与名字一起工作。它应该输出:

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

我知道(我想,我没试过)我可以用 union 和 minus 来做,但我想知道是否可以通过单次选择来做。关于如何做到这一点而又不费力的任何想法?

最佳答案

您几乎可以找到正确的查询答案,但我认为您的搜索有点过头了。只要用“英语”想一想:

  1. 我有类(class)(FROM course)
  2. 其中一些有先决条件(LEFT JOIN prereq)
  3. 我需要先决条件的名称(LEFT JOIN course)

这应该有效:

SELECT
c1.nameco,
c2.nameco AS nameprereq
FROM course AS c1
LEFT JOIN prereq AS p ON p.numcoprereq = c1.numco
LEFT JOIN course AS c2 ON c2.numco = p.numco

关于MySQL:如何进行涉及连接和左连接的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13547436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com