我正在使用ms sqlserver 2005.我有一个查询需要根据日期进行过滤。 可以说我有一个包含电话号码和日期的表格。 我需要提供时间范围内电话号码的计数(开始日期和结束日期)。 如果这些电话号码在过去出现,则不应将其计入结果计数。 我做这样的事情:SQL查询选择优化
select (phoneNumber) from someTbl
where phoneNumber not in (select phoneNumber from someTbl where date<@startDate)
这看起来效率不高,在所有我(和它花费过多时间瓶坯与一些副作用,也许应该在不同的问题,提交的结果) 我在某些TBL中有大约300K行,应该检查。
我做这个检查后,我需要检查一件事。 我有一个过去的数据库,其中包含另一个30K的电话号码。 所以我加入
and phoneNumber not in (select pastPhoneNumber from somePastTbl)
和真正钉棺材或打破骆驼或什么都使用的是解释致命状态短语的最后一根稻草。
所以我正在寻找更好的方法来预制这2个动作。
UPDATE 我已经选择去亚历山大的解决方案,结束了这种查询:
SELECT t.number
FROM tbl t
WHERE t.Date > @startDate
--this is a filter for different customers
AND t.userId in (
SELECT UserId
FROM Customer INNER JOIN UserToCustomer ON Customer.customerId = UserToCustomer.CustomerId
Where customerName = @customer
)
--this is the filter for past number
AND NOT EXISTS (
SELECT 1
FROM pastTbl t2
WHERE t2.Numbers = t.number
)
-- this is the filter for checking if the number appeared in the table before startdate
AND NOT EXISTS (
SELECT *
FROM tbl t3
WHERE t3.Date<@startDate and t.number=t3.number
)
感谢吉拉德
什么部分查询的花费最多时间的查询执行计划?索引是否提供?查询需要多长时间?什么是可接受的时间范围? – jpw 2013-05-01 09:56:01