2011-01-05 63 views
2

我有以下表格:SQL連接數據的

項目(表) 沒有 名 價格 描述

項目定製(表) 用戶ID 爲itemid 說明1 內容描述2

如果一個項目在項目自定義表中有一個描述,我想顯示該描述否則我顯示的項目描述t能夠。

我做了一個查詢,我內心加入item.no = item-custom.itemid項目自定義表。如果項目在項目自定義表格中具有說明,這可以正常工作。但是如果它沒有描述,查詢就不會返回任何數據。

我應該如何編寫這個查詢,所以我總是得到一個項目記錄,無論它是否在項目自定義表中有描述。

這裏是我有:

SELECT item.description, item-custom.description1, item-custom.description 
FROM item 
INNER JOIN item-custom ON item.no = item-custom.itemid 

回答

3

爲此,您可以使用左嘗試聯接,而不是內部的加入。您可以閱讀關於左連接的更多信息here 內連接僅從兩個表中具有非空列的記錄取得。所以如果描述是空的(NULL),記錄將不會顯示。在使用左連接時,它會。

SELECT item.description, item-custom.description1, item-custom.description 
FROM item 
LEFT JOIN item-custom ON item.no = item-custom.itemid 
2
SELECT item.description, item-custom.description1, item-custom.description 
FROM item 
LEFT OUTER JOIN item-custom ON item.no = item-custom.itemid 
0

與where子句來代替

SELECT item.description, item-custom.description1, item-custom.description 
FROM item as item , item-custom as item-custom 
WHERE item.no = item-custom.itemid 
0
SELECT CASE WHEN item-custom.description2 IS NOT NULL 
THEN item-custom.description2 
ELSE item.description END, ... 
1

我覺得它適合更合你的條件

SQL服務器:

SELECT ISNULL(item.description, item-custom.description) as descriptin 
FROM item 
LEFT OUTER JOIN item-custom ON item.no = item-custom.itemid 

MySql的

SELECT COALESCE(item.description, item-custom.description) as descriptin 
FROM item 
LEFT OUTER JOIN item-custom ON item.no = item-custom.itemid 

ISNULLCOALESCE返回第一個非空參數