SQLServer在单个语句中编写联合

时间:2012-03-14 15:20:12

标签: sql-server union

我的查询如下:



SELECT * FROM [PMDB_DEV].[dbo].[TRSRCFIN] 
WHERE proj_id = 167592 
AND taskrsrc_id NOT IN
(
SELECT taskrsrc_id FROM [PMDB_ARC].[dbo].[TRSRCFIN_TEST]
WHERE proj_id = 167592 
)
UNION
SELECT * FROM [PMDB_DEV].[dbo].[TRSRCFIN] 
WHERE proj_id = 167592 
AND fin_dates_id NOT IN
(
SELECT fin_dates_id FROM [PMDB_ARC].[dbo].[TRSRCFIN_TEST]
WHERE proj_id = 167592 
)

基本上,查询返回taskrsrc_id或fin_dates_id不应出现在子查询数据中的所有行。

我可以不使用UNION吗?

谢谢, 马赫什

4 个答案:

答案 0 :(得分:2)

select  * 
from    [PMDB_DEV].[dbo].[TRSRCFIN] t1
where   proj_id = 167592 
        and not exists
        (
        select  *
        from    [PMDB_ARC].[dbo].[TRSRCFIN_TEST] t2
        where   t2.proj_id = t1.proj_id
                and (
                    t1.taskrsrc_id = t2.taskrsrc_id
                    or
                    t1.fin_dates_id = t2.fin_dates_id
                )
        )

答案 1 :(得分:0)

我相信这样做:

SELECT * 
FROM [PMDB_DEV].[dbo].[TRSRCFIN] 
WHERE proj_id = 167592 
and not exists (select null from [PMDB_ARC].[dbo].[TRSRCFIN_TEST]
                 WHERE proj_id = TRSRCFIN.proj_id 
                   and (TRSRCFIN_TEST.taskrsrc_id = TRSRCFIN.taskrsrc_id
                    or TRSRCFIN_TEST.fin_dates_id = TRSRCFIN.fin_dates_id)
               )

答案 2 :(得分:0)

也许是这样的:

SELECT 
    * 
FROM 
    [PMDB_DEV].[dbo].[TRSRCFIN] 
WHERE 
    proj_id =167592 
    AND NOT EXISTS
    (
        SELECT 
            NULL
        FROM 
            [PMDB_ARC].[dbo].[TRSRCFIN_TEST]
        WHERE 
            [PMDB_ARC].[dbo].[TRSRCFIN_TEST].proj_id = [PMDB_DEV].[dbo].[TRSRCFIN].proj_id
            AND 
            (
                [PMDB_ARC].[dbo].[TRSRCFIN_TEST].taskrsrc_id= [PMDB_DEV].[dbo].[TRSRCFIN].taskrsrc_id
                OR  [PMDB_ARC].[dbo].[TRSRCFIN_TEST].fin_dates_id= [PMDB_DEV].[dbo].[TRSRCFIN].fin_dates_id
            )
    )

答案 3 :(得分:0)

为什么?

如果你有正确的索引(一个在proj_id + taskrsrc_id上,一个在proj_id + fin_dates_id上),那么这个UNION查询很可能会使用两个索引并且比不使用的查询更快 UNION(并且不能同时使用这两个索引)。如果有的话,我会更加关注优化*NOT IN