简体   繁体   中英

MySQL: how to make this query involving a join and a left join

This is just a college exercise, so I'm not in a hurry. But I'd like to have the answer already. Consider these tables and rows:

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);

I did not made this. I just translated it and removed some irrelevant bits. I know there are two course rows with the same PK, but I'll have to ask my teacher on this one.

He asked us to write a query to obtain the names of the courses and the names of the course's prerequisites. If it was just the course's number, a left join would do the trick. But I can't make it work with the names. It should output:

course 1    (null)
course 2    course 1
course 3    (null)
course 4    course 2
course 5    (null)
course 6    course 1

I searched a lot and wrote two attempts:

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;

They output, respectively:

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

and

course 2    course 1
course 2    course 5
course 4    course 2
course 4    course 6
course 6    course 1
course 6    course 5

I know (I guess, I haven't tried) I could do it with union and minus, but I want to know if it's possible to do it on a single select. Any idea on how to do that without kludging?

You nearly have the right answer with your queries, but I think your searching a little to far. Just think of it in "english" :

  1. I have courses ( FROM course )
  2. Some of them have prerequisites ( LEFT JOIN prereq )
  3. I need the name of the prerequisite ( LEFT JOIN course )

This should work :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM