简体   繁体   English

SQL Server内部联接和子查询

[英]SQL Server inner join and subquery

I have below the query that updates certain ids on HierarchicalTable . 我在查询下方更新了HierarchicalTable上的某些ID。

My first query, is stable but I have a problem on its performance: 我的第一个查询是稳定的,但我的性能有问题:

DECLARE @targetName varchar(100)
UPDATE a
SET   a.PrimaryId = b.PrimaryId
    , a.SecondaryId = b.SecondaryId
FROM
(
    SELECT PrimaryId
         , SecondaryId
    FROM Hierarchical
    WHERE ParentName = @targetName
) as a
JOIN 
(
    SELECT PrimaryId
         , SecondaryId
    FROM Hierarchical
    WHERE Name = @targetName
) b
ON a.ParentId = b.Id

This next query, is my second option: 下一个查询是我的第二个选择:

DECLARE @targetName varchar(100)

UPDATE a
SET   a.PrimaryId = b.PrimaryId
    , a.SecondaryId = b.SecondaryId
FROM Hierarchical a
JOIN Hierarchical b
ON a.ParentId = b.Id
WHERE a.ParentName = @targetName
  AND b.Name = @targetName

My questions are: 我的问题是:

  1. Does the second query execute just like the first query? 第二个查询是否像第一个查询一样执行?

  2. Will the second query outperform the first query? 第二个查询是否会胜过第一个查询?

*Note: I have large scale of data, and we're having hardware issues on executing these queries. *注意:我有大量数据,我们在执行这些查询时遇到硬件问题。

I've posted here at SO so that I can have any opinions that I can see. 我已经在这里发布了,所以我可以得到任何我能看到的意见。

Your first query will not execute because it is missing an on clause. 您的第一个查询将不会执行,因为它缺少on子句。 Let me assume that the on clause is really a.Id = b.Id . 我假设on子句真的是a.Id = b.Id

The question you are asking is about how the query is optimized. 您要问的问题是如何优化查询。 The real way to answer is to look at the query plan, which you can readily see in SQL Server Management Studio. 回答的真正方法是查看查询计划,您可以在SQL Server Management Studio中轻松查看该计划。 You can start with the documentation to go down this path. 您可以从文档开始沿着这条路走下去。

In your case, though, you are using the subqueries to say "do the filtering when you read the data". 但是,在您的情况下,您使用子查询来说“在读取数据时执行过滤”。 Actually, SQL Server typically pushes such filtering operations down to the table read, so the subqueries are probably superfluous. 实际上,SQL Server通常将这种过滤操作推送到表读取,因此子查询可能是多余的。

If you want to improve performance, I would suggest that you have the following indexes on the table: hierarchical(parentname, id) and hierarchical(name, id) . 如果你想提高性能,我建议你在表上有以下索引: hierarchical(parentname, id)hierarchical(name, id) These should probably give a good performance boost. 这些应该可以提供良好的性能提升。

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

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