用JOIN替换SQL UNION

时间:2012-09-12 15:08:55

标签: sql

我对SQL很新,我对连接有疑问。

我有以下三个表,其中第三个表可以包含有关标题和项目级别的信息

表1 - HEADER

GUID

AAA
BBB
CCC

表2 - 项目

GUID ITEMNR -> Can be 01, 02, ... 99

BBB  01
BBB  02
CCC  01

表3 - ADDINFO

GUID INFO ITEMNR -> If 00 info belongs to header, if > 00 info on item level

AAA  xx   00
BBB  yy   00
BBB  xx   10
CCC  zz   00

现在我想搜索info = xx的guids,但我需要找到guid,其中info = xx(在标题级别)以及其中至少有一个项目有info = xx

的guids

所以结果看起来应该是这样的

GUID ITEMNR
AAA  00
BBB  10  

以下内容可以使用,但它使用UNION:

SELECT H.GUID, I.itemnr
from HEADER as H 
inner join ADDINFO as A on H.guid = A.guid and A.itemnr = '00'
left outer join ITEM as I on I.guid = A.guid 
where 
A.info = 'xx' and
NOT EXIST (SELECT GUID FROM ADDINFO WHERE ADDINFO.guid = I.guid and
ADDINFO.itemnr =     I.itemnr)
UNION
SELECT H2.GUID, I2.itemnr
from HEADER as H2
inner join ADDINFO as A2 on H2.guid = A2.guid and A2.itemnr > '00'
inner join ITEM as I2 on H2.guid = I2.guid 
where A.info = 'xx'

是否有任何SQL专家知道只使用一个选择和连接而不是' union'来获得上述结果的可能性。并且“不存在”' - 在我正在工作的应用程序中,我无法使用UNION或“不存在”。

1 个答案:

答案 0 :(得分:0)

你正试图找到具有特定特征的事物。我认为最好的方法是使用group by和having子句:

select guid
from addinfo
group by guid
having sum(case when info = 'xx' and itemnr = '00' then 1 else 0 end) > 0 or -- items on header level
       sum(case when info = 'xx' and itemnr > '00' then 1 else 0 end) > 0    -- items on the item level

这封装了你的两个条件。它也可以简化为:

select guid
from addinfo
group by guid
having sum(case when info = 'xx' then 1 else 0 end) > 0