CTE优化

时间:2018-09-18 03:13:45

标签: sql sql-server common-table-expression query-performance

我有一个涉及CTE的查询。我只想知道以下查询是否可以最佳化,如果可以,那么优化后的依据是什么?

查询如下:

WITH A AS               
(               
  SELECT                
    user_ID             
  FROM user             
  WHERE user_Date IS not NULL               
),              
B AS                
  (             
      SELECT                
        P.user_ID,              
        P.Payment_Type,             
        SUM(P.Payment_Amount) AS Total_Payment              
      FROM Payment P                
        JOIN A ON A.user_ID = P.user_ID             
  )             
SELECT              
  user_ID,              
  Total_Payment_Amount              
FROM B              
WHERE Payment_Type = 'CR';              

3 个答案:

答案 0 :(得分:1)

您的查询应该使用GROUP BY,因为您似乎希望为每个user_ID求和。从性能的角度来看,您正在引入许多子查询,而这些子查询并不是必需的。我们可以使用Paymentuser表之间的单个联接来编写查询。

SELECT                
    P.user_ID,              
    SUM(P.Payment_Amount) AS Total_Payment              
FROM Payment P                
INNER JOIN user A
    ON A.user_ID = P.user_ID
WHERE
    A.user_Date IS NOT NULL AND P.Payment_Type = 'CR'
GROUP BY
    P.user_ID;

答案 1 :(得分:0)

对于Oracle,SQL Server和Postgres,查询优化器应该可以毫无问题地找到最佳的查询计划。通常,您可以找出数据库将使用EXPLAIN做什么。

答案 2 :(得分:0)

尝试以下查询:

 select  p.user_ID,              
 SUM(Payment_Amount) as Total_Payment_Amount    
 from Payment P join   user u
 on P.user_ID=u.user_ID
 where Payment_Type = 'CR';
 and u.user_Date IS not NULL
 group by p.user_ID

SQL Server 2014