CTE优化

问题描述 投票:-2回答:3

我有一个涉及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';              
sql sql-server common-table-expression query-performance
3个回答
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;

0
投票

对于Oracle,SQL Server和Postgres,查询优化器应该没有问题为此找到最佳查询计划。您可以通常了解数据库对EXPLAIN的作用。


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

© www.soinside.com 2019 - 2024. All rights reserved.