情况如下。我有两个参数要查询: 项目代码 ITEM_TYPE
first_table包含: ITEM_CODE,Item_Characteristics
second_table包含: ITEM_TYPE,Item_Characteristics
我的目标是获得item_characteristics。如果在第一个表中找不到特定项,我想使用Item_type从第二个表中获取它们。
任何方式都可以在一个查询中完成?
我正在使用SQL Server 2012。
答案 0 :(得分:3)
执行此操作的一种方法是使用not exists
:
select t1.Item_Characteristics
from t1
where t1.item_code = @Item_Code
union all
select t2.Item_Characteristics
from t2
where t2.item_type = @Item_Type and
not exists (select 1 from t1 where t1.item_code = @Item_Code);
答案 1 :(得分:2)
如果FULL JOIN
和Item_Code
属于同一类型,您可以尝试使用Item_Type
:
SELECT COALESCE(t1.Item_Characteristics, t2.Item_Characteristics) AS Item_Characteristics
FROM table1 AS t1
FULL JOIN table2 AS t2
ON t1.Item_Code = t2.Item_Type
WHERE COALESCE(t1.Item_Code, t2. Item_Type) = @param
答案 2 :(得分:0)
让我知道这是否有效 -
select isnull(a.Item_Characteristics,b.item_type)
from first_table as a
left join second_table as b
on a.Item_Characteristics = b.Item_Characteristics
where a.Item_code = @itemcode and b.Item_type = @itemtype