1

我有 3 张桌子:

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

两者都organiz包含individu一个address_id. 中的每一行都individu包含一个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

为了让它工作,我使用了一个联合来查询组织的地址 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?

4

2 回答 2

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)
于 2012-05-18T15:09:32.057 回答
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
        )
于 2012-05-18T15:11:20.630 回答