我有这个在MS SQL Server上运行的查询:
SELECT o.phone AS Number, o.code AS Code, o.name AS Name,
o.expireDate AS ExpireDate, o.disabled AS cardStatus, a.disabled AS AccountStatus,
MAX(j.cDate) AS LastUse
FROM [DATAB].[dbo].[Card] AS o
LEFT OUTER JOIN [DATAB].[dbo].[journal] AS j
ON j.phone = o.phone,
[DATAB].[dbo].[CardType] AS ct, [DATAB].[dbo].[Account] AS a,
[DATAB].[dbo].[CardProduct] AS cp
WHERE o.accountProductId = ct.id
AND ct.accountId = a .id
AND a.number = 'XXXXXXXXXX'
AND ct.partnerProductId = cp.id
AND cp.code = 'XXXX'
GROUP BY o.phone, o.code, o.disabled, o.name, o.expireDate, a.disabled
ORDER BY o.name ASC;
我想优化它以便更快地运行,但不要如何开始。
仅供参考,我已经检查了估计的执行计划,DATAB的索引分析。[dbo]。[journal]说它占查询的70%,但没有索引问题消息。
答案 0 :(得分:1)
以下是使用Outer Apply
SELECT o.phone AS Number,
o.code AS Code,
o.name AS Name,
o.expireDate AS ExpireDate,
o.disabled AS cardStatus,
a.disabled AS AccountStatus,
LastUse
FROM [DATAB].[dbo].[Card] AS o
INNER JOIN [DATAB].[dbo].[CardType] AS ct
ON o.accountProductId = ct.id
INNER JOIN [DATAB].[dbo].[Account] AS a
ON ct.accountId = a .id
INNER JOIN [DATAB].[dbo].[CardProduct] AS cp
ON ct.partnerProductId = cp.id
OUTER apply (SELECT Max(cDate)
FROM [DATAB].[dbo].[journal] AS j
WHERE j.phone = o.phone) ou (LastUse)
WHERE a.number = 'XXXXXXXXXX'
AND cp.code = 'XXXX'
ORDER BY o.name ASC;
在phone,cDate
表的journal
列上创建非聚集索引应该有助于查询