简体   繁体   English

T-SQL联合,但不使用临时表从基于另一个表的结果中排除结果?

[英]T-SQL Union, but exclude results from one table based on another without using a temp table?

I am looking to UNION two select statements, but have it so that the second select excludes some results if the first select contains certain records without using a temp table 我正在寻找两个选择语句的UNION,但是要使第二个选择排除某些结果,如果第一个选择包含某些记录而不使用临时表

I am trying to achieve something like this: 我正在尝试实现以下目标:

select customernumber, name into #tempCustomer1 from customers1

select customernumber, name from #tempCustomer1 
UNION
select customernumber, name from customers2 
where customernumber not in (select customernumber from #tempCustomer1)

order by customernumber

Is it possible to do this without a temp table? 没有临时表,是否可以这样做?

It's a bit unclear what your desired end result is, but to answer your question Is it possible to do this without a temp table? 尚不清楚您想要的最终结果是什么,但要回答您的问题, 是否可以在没有临时表的情况下进行此操作? Yes it is - you could do this: 是的,您可以这样做:

select customernumber, name from customers1
UNION
(
select customernumber, name from customers2 
where customernumber not in (select customernumber from customers1)
) 
order by customernumber

This will return a set made up from the rows in customers1 and customers2 with the customer1 ids removed from customers2, I think this is what you want. 这将返回由customers1和customers2中的行组成的集合,其中customers1 id已从customers2中删除,我想这就是您想要的。

If you want to get rid of duplicate rows, this is done by the UNION since you didn't add the ALL option to it. 如果要摆脱重复的行,这是由UNION完成的,因为您没有向其添加ALL选项。

With this test setup: 使用此测试设置:

declare @customers1 table (customernumber int, name char)
declare @customers2 table (customernumber int, name char)

insert @customers1 values (1,'a'),(2,'b')
insert @customers2 values (3,'d'),(4,'e'),(1,'f')

select customernumber, name from @customers1 
UNION
(
select customernumber, name from @customers2 
where customernumber not in (select customernumber from @customers1)
) 
order by customernumber

The output would be: 输出为:

customernumber  name
1   a
2   b
3   d
4   e

Your query with UNION should be doing exactly what you want cause Union discards the duplicate rows from the result set. 您对UNION查询应该完全按照您的要求进行,因为Union会丢弃结果集中的重复行。 So, you can just say 所以,你可以说

select customernumber, name from customers1

UNION

select customernumber, name from customers2

Per your comment, you can use a inline query to achieve the same without using temporary table like 根据您的评论,您可以使用内联查询来实现相同目的,而无需使用临时表,例如

SELECT * FROM
(
select customernumber, name from customers1

UNION

select customernumber, name from customers2
) tab
WHERE customernumber NOT IN (select customernumber from customers1)
ORDER BY customernumber  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM