我有一个涉及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';
您的查询应该使用GROUP BY
,因为您似乎想要为每个user_ID
获取总和。从性能的角度来看,您引入了许多子查询,这些子查询并不是必需的。我们可以使用Payment
和user
表之间的单个连接来编写查询。
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;
对于Oracle,SQL Server和Postgres,查询优化器应该没有问题为此找到最佳查询计划。您可以通常了解数据库对EXPLAIN
的作用。
尝试以下查询 - :
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