我需要使用LEFT OUTER JOIN在SQL Server中组合两个SQL查询的结果。
查询1:
SELECT dbo.saitem.itm_id, dbo.saitem.itm_num, dbo.saitemcls.cde_id
FROM dbo.saitem INNER JOIN
dbo.saitemcls ON dbo.saitem.itm_id = dbo.saitemcls.itm_id
WHERE (dbo.saitemcls.cde_id = 109)
查询2:
SELECT dbo.sacatalog.cat_name, dbo.sacatalogitem.itm_id
FROM dbo.sacatalogitem INNER JOIN
dbo.sacatalog ON dbo.sacatalogitem.cat_id = dbo.sacatalog.cat_id
WHERE (dbo.sacatalog.cat_name = 'CATALOG1')
我需要从查询1返回dbo.saitem.itm_id和dbo.saitem.itm_num,其中dbo.saitem.itm_id不在查询2中,匹配dbo.saitem.itm_id(查询1)和dbo.sacatalogitem。 itm_id(查询2)。
SQL Server服务器是2005年。
答案 0 :(得分:1)
您可以使用相关的子选择:
select
i.itm_id,
i.itm_num
from
dbo.saitem i
inner join
dbo.saitemcls c
on i.itm_id = c.itm_id
where
c.cde_id = 109 and
not exists (
select
'x'
from
dbo.sacatalogitem ci
inner join
dbo.sacatalog s
on ci.cat_id = s.cat_id
where
s.cat_name = 'CATALOG1' and
i.itm_id = ci.itm_id -- note this refers to the outer query
);
答案 1 :(得分:0)
您可以使用LEFT连接并检查NULL,如下所示:
SELECT dbo.saitem.itm_id, dbo.saitem.itm_num, dbo.saitemcls.cde_id
FROM dbo.saitem
JOIN dbo.saitemcls ON dbo.saitem.itm_id = dbo.saitemcls.itm_id AND dbo.saitemcls.cde_id = 109
LEFT JOIN dbo.sacatalogitem ON dbo.saitem.itm_id = dbo.sacatalogitem.itm_id
LEFT JOIN dbo.sacatalog ON dbo.sacatalogitem.cat_id = dbo.sacatalog.cat_id AND dbo.sacatalog.cat_name = 'CATALOG1'
WHERE dbo.sacatalog.cat_ID IS NULL