cnblogs/dcrenl/SQL Server中取两个表的交集,并集和差集.html

30 lines
1.1 KiB
HTML
Raw Normal View History

2024-09-24 12:43:01 +08:00
<p>在项目中遇到要取两个表差集的情况</p>
<p>假设有两个表tblNZPostCodes, NZPostcode &nbsp;两个表中存储的都是新西兰的post code信息字段一致只是数据上有所差异。</p>
<p>&nbsp;</p>
<p>1. Union &nbsp;获取两个表的合集并且自动过滤重复数据</p>
<div class="cnblogs_code">
<pre>Select * from tblNZPostCodes
Union
Select * from NZPostcode</pre>
</div>
<p>2. Union all 获取两个表的合集并且不过滤重复数据&nbsp;</p>
<div class="cnblogs_code">
<pre>Select * from tblNZPostCodes
Union all
Select * from NZPostcode</pre>
</div>
<p>3. Intersect 获取两个表的交集</p>
<div class="cnblogs_code">
<pre>Select * from tblNZPostCodes
intersect
Select * from NZPostcode</pre>
</div>
<p>4. except 获取第1个表中存在而第2个表中不存在的数据</p>
<p>&nbsp; &nbsp; 比如下面的语句将获取在tblNZPostCodes中存在但NZPostcode中不存在的数据</p>
<div class="cnblogs_code">
<pre>Select * from tblNZPostCodes
except
Select * from NZPostcode</pre>
</div>
<p>&nbsp;</p>
<p>转自https://www.cnblogs.com/wphl-27/p/5488080.html</p>