MySQL:如何使这个查询涉及连接和左连接

时间:2012-11-25 01:26:26

标签: mysql join left-join outer-join

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

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

我知道(我想,我还没试过)我可以用联盟和减号来做,但我想知道是否可以在单个选择上进行。如果没有kludging怎么做呢?

1 个答案:

答案 0 :(得分:1)

您的查询几乎可以得到正确的答案,但我认为您的搜索有点远。只需用“英语”来想一想:

  1. 我有课程(FROM course
  2. 其中一些人有先决条件(LEFT JOIN prereq
  3. 我需要先决条件的名称(LEFT JOIN course
  4. 这应该有效:

    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