What are your most common sql optimizations?

后端 未结 17 1611
谎友^
谎友^ 2020-12-12 14:51

What are your most common SQL optimization that you used?

17条回答
  •  旧巷少年郎
    2020-12-12 15:17

    1) I've yet to find a situation where

    SELECT Field1, Field2, (SELECT Count(*) FROM tblLinked WHERE tblLinked.Field3 = tblSource.Field3) AS TheTotal
    FROM tblSource
    

    isn't improved by a LEFT JOIN to a derived table.

    SELECT Field1, Field2, IsNull(Linked.TheTotal,0) AS TheTotal
    FROM tblSource
    LEFT JOIN (SELECT Field3, Count(*) AS TheTotal
        FROM tblLinked
        GROUP BY Field3) AS Linked ON tblSource.Field3 = Linked.Field3
    

    2) Don't sort the results on the server unless the consuming app is unable to do this itself. This applies less often to web apps, but for desktop apps the client PC usually has plenty of power available and can happily do a sort.

    3) Use EXISTS instead of checking the Count of matching entries.

    4) Don't get obsessed with doing a query in just one SELECT clause. Judicious use of table variables (and sometimes temporary tables) can massively reduce the rows processed.

提交回复
热议问题