查询数据,试图避免使用联盟

时间:2012-05-18 15:05:48

标签: sql sql-server tsql

我有3张桌子:

organiz: pk = org_id
individu: pk = ind_id
address: pk = address_id

organizindividu都包含address_idindividu中的每一行都包含org_id。基本上,“个人”属于“组织”。我想要一个查询,它会向我提供具有特定address_id的所有人的org_id

这是我之前尝试过的,但它只为我所有的个人提供了address_id

select
    a.Address_id,
    a.Address_Line_1,
    a.Address_Line_2,
    a.Address_City,
    a.Address_State_Code,
    a.Address_Zip,
    o.Phone_Number

from
    address a inner join individu i on a.address_id = i.address_id
    inner join organiz o on o.org_id = i.org_id
where
    a.Address_Line_1 is not null
    and o.org_id = 808474

为了使它工作,我使用了一个union来查询组织的地址ID:

select
    a.Address_id,
    a.Address_Line_1,
    a.Address_Line_2,
    a.Address_City,
    a.Address_State_Code,
    a.Address_Zip,
    o.Phone_Number

from
    address a inner join individu i on a.address_id = i.address_id
    inner join organiz o on o.org_id = i.org_id
where
    a.Address_Line_1 is not null
    and o.org_id = 808474
UNION
select
    a.Address_id,
    a.Address_Line_1,
    a.Address_Line_2,
    a.Address_City,
    a.Address_State_Code,
    a.Address_Zip,
    o.Phone_Number
from 
    address a inner join organiz o on a.address_id = o.address_id
where
    o.org_id = 808474
    and a.Address_Line_1 is not null

是否有其他方法可以避免使用UNION?

2 个答案:

答案 0 :(得分:0)

是的,你可以。

Select StuffYouWant 
From Address 
WHERE EXISTS (SELECT * 
                FROM organiz 
                WHERE Address.address_id = organiz.address_id 
                    AND SEARCH_CRITERIA) 
    OR EXISTS (SELECT * 
                FROM individu
                WHERE Address.address_id = individu.address_id 
                AND SEARCH_CRITERIA)

答案 1 :(得分:0)

您可以将UNION推送到内部查询中:

SELECT  a.*
FROM    address
WHERE   id IN
        (
        SELECT  ad.address_id
        FROM    organiz o
        CROSS APPLY
                (
                SELECT  address_id
                UNION ALL
                SELECT  i.address_id
                FROM    individu i
                WHERE   i.org_id = o.org_id
                ) ad
        WHERE   o.org_id = @myorgid
        )