首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >结合具有不同连接条件的两个查询

结合具有不同连接条件的两个查询
EN

Stack Overflow用户
提问于 2019-02-25 16:25:38
回答 2查看 54关注 0票数 0

我有两个不同的查询,它们具有完全相同的SELECTWHERE条件,但它们具有不同的JOIN条件。

我正试图找到一种将这两者结合到一个查询中的方法,而我唯一能够想到的就是使用UNION。有什么不同的或者更好的方法来完成同样的事情吗?

下面是我想要做的事情的一个例子:

代码语言:javascript
复制
create table #Account
(
    ID int, 
    FirstName varchar(25), 
    LastName varchar(25), 
    CodeA int, 
    CodeB int
)

create table #AccountMap
(
    CodeA int,
    CodeB int,
    MapType varchar(25)
)

insert into #Account 
values (1, 'Bob', 'Smith', 424, 867), (2, 'John', 'Davis', 543, NULL), (3, 'Mary', 'Brown', 654, 345)

insert into #AccountMap
values (424, 867, '1-1'), (543, NULL, 'A Only'), (654, 345, '1-1'), (NULL, 391, NULL)

-- Query #1
select ID, MapType
from #Account A
join #AccountMap M on M.CodeA = A.CodeA and M.CodeB = A.CodeB
where MapType is not null

-- Query #2
select ID, MapType
from #Account A
join #AccountMap M on M.CodeA = A.CodeA
where MapType is not null

-- Combined results
select ID, MapType
from #Account A
join #AccountMap M on M.CodeA = A.CodeA and M.CodeB = A.CodeB
where MapType is not null
union
select ID, MapType
from #Account A
join #AccountMap M on M.CodeA = A.CodeA
where MapType is not null

drop table #Account, #AccountMap

我想要的输出是我提供的示例中组合查询的结果(这是两个查询的不同组合)。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-25 16:30:03

像这样怎么样?

这会给你第一个当它存在的时候,第二个当它不存在的时候。

代码语言:javascript
复制
Select ID, COALESCE(M1.MapType, M2.MapType) as MapType
from #Account A
left join #AccountMap M1 on M1.CodeA = A.CodeA and M1.CodeB = A.CodeB
left join #AccountMap M2 on M2.CodeA = A.CodeA
where COALESCE(M1.MapType, M2.MapType) is not null
票数 2
EN

Stack Overflow用户

发布于 2019-02-25 16:39:40

你可以试试这个。

代码语言:javascript
复制
Select ID,MapType from #account a left Join #AccountMap b 
on a.CodeA=b.CodeA 
or a.CodeB=b.CodeB
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54870615

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档