简体   繁体   中英

SQL Server inner join and subquery

I have below the query that updates certain ids on HierarchicalTable .

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. Let me assume that the on clause is really 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. 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.

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) . These should probably give a good performance boost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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