The query is executing very slowly, is there any way to improve it any further?

后端 未结 8 1128
长情又很酷
长情又很酷 2021-02-15 17:26

I have the following query, and because of a lot of SUM function calls, my query is running too slow. I have a lot of records in my database and I would like to get

8条回答
  •  遇见更好的自我
    2021-02-15 18:03

    As it has been mentioned already, the execution plan will be really helpful in this case. Based on what you've shown it seems you have extracted 12 columns of 15 total columns from tb1 (a), so you can try to run your query without any join and just against the tb1 to see whether your query is working as expected. Since I can see nothing wrong with your SUM function calls, my best guess is you have an issue with your joins, I would suggest to do the following. You can start by excluding the last join for instance, INNER JOIN tb5 e on c.col7 = e.id and any related usage of it like e.Class as [Class] and e.Class in your group by statement. We are not going to exclude it completely, this is just a test to make sure whether the problem is with that or not, if your query runs better and as expected you can try to use a temp table as a workaround instead of the last join, something like this:

    SELECT *
    INTO #Temp
    FROM
      (
         select * from tb5
      ) As tempTable;
    
    SELECT 
        b.id as [ID]
        ,d.[Title] as [Title]
        ,e.Class as [Class]
    
        -- SUM Functions
    
    FROM 
        tb1 a
    INNER JOIN 
        tb2 b on a.id=b.fid and a.col3 = b.col4
    INNER JOIN 
        tb3 c on b.fid = c.col5
    INNER JOIN       
        tb4 d on c.id = d.col6
    INNER JOIN 
        #Temp e on c.col7 = e.id
    GROUP BY
        b.id, d.Title, e.Class
    

    Actually, Temporary tables are tables that exist temporarily on the SQL Server. The temporary tables are useful for storing the immediate result sets that are accessed multiple times. You can read more about it here https://www.sqlservertutorial.net/sql-server-basics/sql-server-temporary-tables/ And here https://codingsight.com/introduction-to-temporary-tables-in-sql-server/

    Also I would strongly recommend, if you are using the Stored Procedure, set the NOCOUNT to ON, it can also provide a significant performance boost, because network traffic is greatly reduced:

    SET NOCOUNT ON
    SELECT *
    INTO #Temp
    -- The rest of code
    

    Based on this:

    SET NOCOUNT ON is a set statement which prevents the message which shows the number of rows affected by T-SQL query statements. This is used within stored procedures and triggers to avoid showing the affected rows message. Using SET NOCOUNT ON within a stored procedure can improve the performance of the stored procedure by a significant margin.

提交回复
热议问题