2012-11-25 78 views
2

這只是一個大學演習,所以我不急。但我想已經有了答案。考慮這些表格和行:MySQL:如何使這個查詢涉及加入和左連接

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

您幾乎有正確的答案與您的查詢,但我認爲你的搜索有點遠。想想吧,在 「英語」:

  1. 我有課程(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 
+0

感謝您的答案,但你得到它的倒退。在'ON'子句中,切換'p.'屬性。這是我想要的答案。我從未想過使用兩個左連接。我想更詳細地瞭解這些查詢是如何執行的,以瞭解爲什麼我的嘗試沒有奏效。再次感謝您的答覆。 – GuiRitter