2013-10-31 79 views
6

我有表是這樣的:SQL:連接表顯示空值以及

表1:

id | item_name | entered_by | modify_by 
1 | banana |  2  | 1 
2 | apple  |  4  | 3 
3 | orance |  1  | 1 
4 | pineapple |  5  | 3 
5 | grape  |  6  | 1 

表2:

id | username 
1 | admin 
2 | jack 
3 | danny 
4 | dummy 
5 | john 
6 | peter 

查詢是做工精細的選擇,如果entered_by或modify_by具有價值:

SELECT t1.id, t1.item_name, 
    t2enteredBy.username enteredBy, 
    t2modifyBy.username modifyBy 
FROM table1 t1 
JOIN table2 t2enteredBy ON t1.entered_by = t2enteredBy.id 
JOIN table2 t2modifyBy ON t1.modify_by = t2modifyBy.id 

問題:如果其中一個modifiy_by或entered_by字段具有空值,則該行現在顯示出來,如果它具有空值而不是完全隱藏該行,則需要將其顯示爲「 - 」。

SQLFIDDLE HERE

+0

使用LEFT JOIN,而不是加入 –

+0

使用'LEFT JOIN's和'COALESCE'。 – geomagas

回答

6

嘗試了這一點:

SELECT t1.id, t1.item_name, 
    COALESCE(t2enteredBy.username, '-') enteredBy, 
    COALESCE(t2modifyBy.username, '-') modifyBy 
FROM table1 t1 
LEFT JOIN table2 t2enteredBy ON t1.entered_by = t2enteredBy.id 
LEFT JOIN table2 t2modifyBy ON t1.modify_by = t2modifyBy.id 

小提琴here

您需要一個left join才能返回具有null值的那些行。然後​​3210將確保它們被替換爲給定的字符串,如果它們是null

+1

熾烈的快速:)它的作品!謝謝 – Teddybugs

1

試試這個 - 使用LEFT JOIN代替JOIN

SELECT t1.id, t1.item_name,ifnull(t2enteredBy.username,'-') enteredBy, 
    ifnull(t2modifyBy.username,'-') modifyBy 
FROM table1 t1 
LEFT JOIN table2 t2enteredBy ON t1.entered_by = t2enteredBy.id 
LEFT JOIN table2 t2modifyBy ON t1.modify_by = t2modifyBy.id 

SQL Fiddle Here

+0

這不會處理空值。該OP是要求,如果值爲空,然後' - ' – Arion

+0

謝謝阿里昂,只需更新與小提琴的答案 –

+0

我很可能會使用COALESCE。因爲你不知道他使用MYSQL – Arion