【发布时间】:2019-08-09 07:24:57
【问题描述】:
我的查询有问题。我在这里有一个简单的例子来说明我的代码。
SELECT distinct ID
FROM Table
WHERE IteamNumber in (132,434,675) AND Year(DateCreated) = 2019
AND ID NOT IN (
SELECT Distinct ID FROM Table
WHERE IteamNumber in (132,434,675) AND DateCreated < '2019-01-01')
如您所见,我正在检索在 2019 年而非更早时间创建的唯一数据 ID。
select 语句工作正常,但是一旦我使用 NOT IN 语句,查询可能会轻松超过 1 分钟。
我的另一个问题可能与运行 Microsoft Business Central 的 SQL Server 的计算机/服务器性能有关吗?因为即使使用 (NOT IN) 语句,同样的查询也能完美运行,但那是在 Microsoft Dynamics C5 SQL Server 中。
所以我的问题是我的查询有问题还是主要是服务器问题?
更新:这是一个真实的例子:检索 500 行需要 25 秒
Select count(distinct b.No_),'2014'
from [Line] c
inner join [Header] a
on a.CollectionNo = c.CollectionNo
Inner join [Customer] b
on b.No_ = a.CustomerNo
where c.No_ in('2101','2102','2103','2104','2105')
and year(Enrollmentdate)= 2014
and(a.Resignationdate < '1754-01-01 00:00:00.000' OR a.Resignationdate >= '2014-12-31')
and NOT EXISTS(Select distinct x.No_
from [Line] c
inner join [Header] a
on a.CollectionNo = c.CollectionNo
Inner join [Customer] x
on x.No_ = a.CustomerNo
where x.No_ = b.No_ and
c.No_ in('2101','2102','2103','2104','2105')
and Enrollmentdate < '2014-01-01'
and(a.Resignationdate < '1754-01-01 00:00:00.000' OR a.Resignationdate > '2014-12-31'))
【问题讨论】:
-
如果不了解更多关于您的数据库的信息,实际上无法回答这个问题,例如多少行,什么索引等。要获得实际的性能帮助,您确实需要向我们展示您的执行计划。
-
关注这个话题:NOT IN vs NOT EXISTS
-
在您的第一个查询中,您只包括那些日期在 2019 年创建的 ID。它将自动不包括任何具有“DateCreated
-
将
Year(DateCreated) = 2019替换为DateCreated >= '2019-01-01'并放弃NOT IN。 -
@Ritika,如果 ID 不是唯一的,这是不正确的:
It will automatically not include any of the ID that have 'DateCreated < '2019-01-01
标签: sql-server notin dynamics-business-central