优化比较不同数据库中具有相似架构的两个表的查询
我在不同的数据库中有两个具有相似架构的不同表。比较这两个表之间的记录的最佳方法是什么?我需要找出—— 第一个表中存在但第二个表中不存在相应记录的记录,使用一些 where 子句过滤第一个表中的记录。 到目前为止,我已经有了这个 SQL 构造:
Select t1_col1, t1_ col2 from table1
where t1_col1=<condition> AND
t1_col2=<> AND
NOT EXISTS
(SELECT * FROM
table2
WHERE
t1_col1=t2_col1 AND
t1_col2=t2_col2)
有更好的方法吗?
上面的查询看起来不错,但我怀疑它是在进行逐行比较,而不评估查询第一部分中的条件,因为查询的第一部分会大大减少结果集。这种情况发生了吗?
I have two different tables with similar schema in different database. What is the best way to compare records between these two tables. I need to find out-
records that exists in first table whose corresponding record does not exist in second table filtering records from the first table with some where clauses.
So far I have come with this SQL construct:
Select t1_col1, t1_ col2 from table1
where t1_col1=<condition> AND
t1_col2=<> AND
NOT EXISTS
(SELECT * FROM
table2
WHERE
t1_col1=t2_col1 AND
t1_col2=t2_col2)
Is there a better way to do this?
This above query seems fine but I suspect it is doing row by row comparison without evaluating the conditions in the first part of the query because the first part of the query will reduce the resultset very much. Is this happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用
except
关键字即可!!!它返回操作数左侧查询中的任何不同值,但右侧查询中未返回的值除外。
有关 MSDN 的详细信息
Just use
except
keyword!!!It returns any distinct values from the query to the left of the EXCEPT operand that are not also returned from the right query.
For more information on MSDN
如果希望两个表中的数据具有相同的主键,则可以使用 IN 关键字来过滤那些在另一个表中找不到的数据。这可能是最简单的方法。
如果您愿意使用第三方工具,例如 Redgate Data Compare 你可以尝试一下,这是一个非常好的工具。 Visual Studio 2010 Ultimate版也有这个功能。
If the data in both table are expected to have the same primary key, you can use IN keyword to filter those are not found in the other table. This could be the simplest way.
If you are open to third party tools like Redgate Data Compare you can try it, it's a very nice tool. Visual Studio 2010 Ultimate edition also have this feature.