SQL Sub-query or INNER-JOIN?

后端 未结 4 961
执笔经年
执笔经年 2021-01-13 05:38

I\'ve the two following queries:

declare @UserId as int
set @UserId = 1

-- Query #1: Sub-query
SELECT
    u.[Id] ,
    u.[Name] ,
    u.[OrgId] AS Organizat         


        
4条回答
  •  清歌不尽
    2021-01-13 06:34

    It will depend largely on the cardinality of your data: if your in-line lookups are minimal compared to the overhead of joining vast amounts of data (when you only need to extract a small subsection from that join result), then the inline option will be quicker. But if you are having substantial overhead with in-line selects (i.e. if your result has a large number of rows, and you are calling out an inline select for each and every row), then the join will be quicker.

    I can't see from yourquestion the numbers involved (i.e. how many rows) so it's hard to make qualitative comment.

    For example, if your result set has 10 rows, then the inline selects will be carried out for each of those ten rows only, whereas the join might be involving far more rows, which are then selectively reduced by WHERE clauses. But if you have a resultset of 10 million rows, the inline selects will most probably kill performance, since its row-by-row.

    EXAMPLE: imagine you have to collect a load of bricks (specified by size etc.) from all over a building yard and paint them blue.

    inline select = Selecting all the bricks you need and then painting them by hand.

    join = dump all the bricks into a huge bucket of paint, anf then choose the ones you need

    If you only want to end up with 10 bricks, it is far quicker to select and then paint by hand. If you want a million bricks, then mass-painting them in a tub first is the way to go.

提交回复
热议问题