sql - SQL-Server Using "USE" with INNER JOINS and "UNION" together
问题描述
I've seen plenty of documentation on UNION
and INNER JOIN
in the same query, but I cannot find documentation on this specific case.
Here's an example of what I'm trying to do, but this syntax is invalid:
USE DB1
SELECT DISTINCT ResourceTable.ID, CustomerTable.FN
FROM ResourceTable
INNER JOIN CustomerTable ON ResourceTable.CID = CustomerTable.CID
UNION ALL
USE DB2
SELECT DISTINCT ResourceTable.ID, CustomerTable.FN
FROM ResourceTable
INNER JOIN CustomerTable ON ResourceTable.CID = CustomerTable.CID
ORDER BY ResourceTable.ID
So basically, there are two databases that have identical schema but different data. I need to run an INNER JOIN
query on both of them, and one way I imagined that might work is a UNION
.
This would all work except for Line 6, where I am attempting to reference another database. I'm wondering if there is a way to make this work and I'm just getting the syntax wrong.
One option would be to insert both into a ##temp
table and then query the temp table, but I'd like to avoid that if possible.
解决方案
很容易的一个。试试下面的代码:
SELECT DISTINCT ResourceTable.ID, CustomerTable.FN
FROM DB1.dbo.ResourceTable AS ResourceTable
INNER JOIN DB1.dbo.CustomerTable AS CustomerTable
ON ResourceTable.CID = CustomerTable.CID
UNION ALL
SELECT DISTINCT ResourceTable.ID, CustomerTable.FN
FROM DB2.DBO.ResourceTable AS ResourceTable
INNER JOIN DB2.DBO.CustomerTable AS CustomerTable
ON ResourceTable.CID = CustomerTable.CID
ORDER BY ResourceTable.ID;
这是考虑到如果表在其他模式下,您正在使用默认模式“dbo”,只需将 dbo 替换为任何模式即可。
这种方式对于归档不同数据库之间的数据、比较数据或在不同数据库中的表之间进行任何连接非常有用。
推荐阅读
- excel - 如何插入值并从多个工作表中获取结果
- python - 从两个数据帧计算一个新的熊猫数据帧
- c - 将 3D 数组保存到文件的问题
- c# - 按排序列表排序的随机字母C#
- ios - 无法使用“String”类型的索引为“[NSObject : AnyObject]”类型的值下标
- c - 使用 malloc 的指针数组:代码遇到分段错误。帮助!谢谢
- entity-framework - 具有多个关键参数的多对多自引用
- c++ - 错误:“operator+”不匹配(操作数类型为“const QString”和“QDate”)
- javascript - 理解 javascript return 语句为什么返回 undefined
- java - 在服务器 tomcatv 8.5 上部署 maven 项目时出错