簡體   English   中英

SQL連接其他表中的數據

[英]SQL joining data from other tables

我有以下表格:

項目(表)無名稱價格說明

項目自定義(表)用戶標識itemid description1 description2

如果項目在“項目自定義”表中有描述,我想顯示該描述,否則我正在顯示項目表中的描述。

我做了一個查詢,在其中我內部連接了item.no = item-custom.itemid上的item-custom表。 如果該項目在item-custom表中有說明,則可以正常工作。 但是,如果沒有描述,查詢將不會返回任何數據。

我應該如何編寫此查詢,以便無論是否在item-custom表中有描述,我總是會得到一個項目記錄。

這是我所擁有的:

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

您可以使用左聯接而不是內部聯接來執行此操作。 您可以在此處了解有關左聯接的更多信息。內部聯接僅從兩個具有不可空列的表中獲取記錄。 因此,如果描述為空(NULL),則不會顯示該記錄。 當使用左聯接時,它將。

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

我認為它更適合您的情況

SQL Server:

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返回第一個非NULL參數

嘗試使用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
SELECT CASE WHEN item-custom.description2 IS NOT NULL 
THEN item-custom.description2 
ELSE item.description END, ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM