2017-04-16 105 views
0

嗨我試圖查詢是要顯示每個4表中的4個值。MySQL選擇連接空值

select i.name, c.name, s.name, d.name 
from instructor i 
join course c 
    on i.pid = c.instructor 
join course_taken ct 
    on c.id = ct.cid 
join student s 
    on s.id = ct.sid 
join department d 
    on s.major = d.id or s.major is null 
where i.name = 'lee'; 

一切都很好,除了零部分。

表結構

-------------------------------------------------- 
| student | course | instructor | department | 
-------------------------------------------------- 
| name | name  | id   | id   | 
-------------------------------------------------- 
| id  | id  | name  | name   | 
-------------------------------------------------- 
| major |instructor| department |    | 
-------------------------------------------------- 

結果

-------------------------------------------------- 
| i.name | c.name | s.name | d.name   | 
-------------------------------------------------- 
| kim  | math | jack | cs    | 
-------------------------------------------------- 
| kim  | math | john | cs    | --> THIS VALUE IS 
-------------------------------------------------- 
| kim  | math | john | ss    | --> NULL AND SHOULD BE PRINTED IN NULL 
-------------------------------------------------- 
| kim  |math  | json | ss    | 
-------------------------------------------------- 

如何打印空當 'CS' 和 'SS' 在 「約翰」 是NULL?

回答

0

使用COALESCE()

select coalesce(i.name,'NULL') as iName, ... 
from instructor i 

根據您的評論功能看起來你不想有從department表輸出的name列在所有。在這種情況下,只需選擇NULL它喜歡

select i.name, c.name, s.name, null 

(OR)

select i.name, c.name, s.name, 'null' 
+0

謝謝你讓我知道該功能。我試圖隱藏主要(CS或SS如果NULL)。我嘗試從教師i'選擇i.name,c.name,s.name,coalesce(d.name,'NULL') ,沒有工作。仍然在主要列中獲得'cs'和'ss':( – Gomtting

+0

@Gomtting,請參閱編輯答案,如果有幫助 – Rahul

+0

哦,對不起,我想我沒有意識到我從上面選擇的名稱..我編輯表我需要主要的名字,即使它是NULL,就像'cs/cs/ss/ss'到'cs/NULL/NULL/ss'。 – Gomtting