SQL从其他表加入数据

时间:2011-01-05 10:15:23

标签: sql

我有以下表格:

项目(表) 没有 名称 价钱 描述

物品定制(表) 用户身份 的itemid 说明1 说明2

如果某个项目在项目自定义表格中有描述,我想显示该描述,否则我将显示项目表格中的描述。

我做了一个查询,其中我在item.no = item-custom.itemid上加入item-custom表。如果项目在项目自定义表中有描述,则此工作正常。但如果它没有描述,则查询不会返回任何数据。

我应该如何编写此查询,以便无论项目自定义表中是否有描述,我都会获得项目记录。

这就是我所拥有的:

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

5 个答案:

答案 0 :(得分:3)

您可以使用左连接而不是内连接来执行此操作。您可以阅读有关左联接的更多信息here 内部联接仅从具有非可空列的两个表中获取记录。因此,如果description为空(NULL),则不会显示记录。使用左连接时,它会。

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

我认为这更适合你的病情

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参数

答案 3 :(得分: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

答案 4 :(得分:0)

SELECT CASE WHEN item-custom.description2 IS NOT NULL 
THEN item-custom.description2 
ELSE item.description END, ...
相关问题