如何使用 sql server exists 子句进行优化?
Posted
技术标签:
【中文标题】如何使用 sql server exists 子句进行优化?【英文标题】:How to do optimization with sql server exists clause? 【发布时间】:2016-07-28 06:51:53 【问题描述】:我有一个包含 exists 子句的 sql 查询。以前在两个表之间存在内部联接,但由于一些新条件,我用存在子句替换了内部联接。以下是我的查询-
SELECT id,
Count(id) AS 'ItemCount'
FROM table1 t1
WHERE ( EXISTS(SELECT DISTINCT messageid
FROM table2 t2
WHERE t2.messageid = t1.chatmessageid
AND t2.receiverid = 'xyzo-1234'
AND t2.groupid = 'wxfx-1234'
AND ( t1.userid = 'ttew-3457'
OR t1.userid IS NULL ))
OR ( t1.userid = 'ttew-3457' ) )
AND ( t1.machineid != 'C34F-A609' )
AND ( t1.createdtime > '2016-07-20 :: 07:21:51.9118534' )
AND ( t1.createdtime <= '2016-07-27 :: 13:25:30.1016155' )
AND ( t1.groupid = 'wxfx-1234' )
GROUP BY t1.id
ORDER BY t1.id
但是这个查询比上一个查询花费了更多的时间,我想进一步优化它。谁能建议我如何进一步优化此查询?
【问题讨论】:
好吧,对于初学者来说,DISTINCT
在 EXISTS
中毫无意义,因为它只关心 0 行和多于 0 行之间的区别。
EXISTS(...OR t1.UserId IS NULL
- 你确定吗?
如果你有可以有 NULL 值的列,用类似isnull(t1.UserId, '')
的东西重写
我建议您开始使用DATETIME2
数据类型来存储日期+时间信息。这将使比较/查找更快。
【参考方案1】:
SELECT Id, COUNT(Id) as 'ItemCount'
FROM table1 t1 WHERE (
EXISTS(
***SELECT Count 1 0 FROM table2 t2***
WHERE t2.MessageId = t1.ChatMessageId AND t2.ReceiverId ='xyzo-1234'
AND t2.GroupId='wxfx-1234'
AND (t1.UserId ='ttew-3457' OR t1.UserId IS NULL)
)
OR (t1.UserId ='ttew-3457')
)
AND (t1.MachineId != 'C34F-A609') AND (t1.CreatedTime > '2016-07-20 :: 07:21:51.9118534')
AND (t1.CreatedTime <= '2016-07-27 :: 13:25:30.1016155') AND (t1.GroupId='wxfx-1234')
GROUP BY t1.Id
ORDER BY t1.Id
【讨论】:
以上是关于如何使用 sql server exists 子句进行优化?的主要内容,如果未能解决你的问题,请参考以下文章