我有一个查询大约需要 2 秒才能获取 16,900 行:
SELECT x.lid
FROM schema1.view1 x
INNER JOIN schema1.view2 y
ON x.cid = y.cid
and datediff(day, x.indt, y.linvcy)=0 -- problematic line
and x.indt = y.indt -- alternative line I've tried
但是,如果我将时间比较(最后一行)添加到连接逻辑中,则查询需要一个多小时才能执行(我实际上从未能够完成它)。
每个视图本身都包含连接逻辑,因此查询计划的复杂度相当高。我正在寻找一些指针来帮助优化此查询。
schema1.view1
:
select
D.lid,
D.cid,
D.indt,
lower(trim(substring(C.bse, 1, charindex('-', C.bse)-1))) as bse
from (
select
B.lid,
B.cid,
B.indt
from ds.v A
inner join (
select
x.lid,
x.cid,
x.ivid,
x.clior,
x.sosy,
x.indt
from rd.ui x
where
x.clior like 'abc'
) B
on
B.ivid like A.ivn
and B.clior like A.clior
) D
left join ctlg.brchs C
on
C.paor like D.clior
and C.sosy like D.sosy
and C.bid like D.cid
rd.ui
:
create table rd.ui (
id int identity(1,1) primary key,
lid varchar(256),
cid varchar(256),
ivid varchar(256),
indt date,
clior varchar(256),
sosy varchar(256)
)
create unique index idx_unlid
on rd.ui(lid)
create index idx_sebid
on rd.ui(bid)
create index idx_seindt
on rd.ui(indt)
create index idx_sec
on rd.ui(clior)
ctlg.brchs
:
create table ctlg.brchs (
id int identity(1,1) primary key,
paor varchar(256),
sosy varchar(256),
bid varchar(256)
)
create unique index idx_unbr
on ctlg.brchs (paor, sosy, bid)
schema1.view2
:
SELECT
A.cid
, A.cinvcy
, B.linvcy
FROM (
SELECT
x.cid
, MAX(x.indt) AS cinvcy
FROM schema1.view1 x
GROUP BY
x.cid
) A
INNER JOIN (
SELECT
z.cid
, MAX(z.indt) AS linvcy
FROM (
SELECT
x.cid
, x.indt
FROM schema1.view1 x
WHERE CONCAT(x.cid, x.ind) NOT IN (
SELECT CONCAT(y.cid, MAX(y.indt))
FROM schema1.view1 y
GROUP BY y.cid
)
) z
GROUP BY
z.cid
) B
ON A.cid=B.cid
我尝试使用
with schemabinding
创建索引视图,但这些视图包含 CTE 和派生表 (select * from (select * from x)
),这意味着我无法在这些视图上创建索引。
更新:将
like
更改为 =
显着提高了该部分查询的速度,但其余部分仍然非常慢。
在
schema1.view2
中,这个CONCAT
匹配很奇怪。
SELECT
x.cid
, x.indt
FROM schema1.view1 x
WHERE CONCAT(x.cid, x.ind) NOT IN (
SELECT CONCAT(y.cid, MAX(y.indt))
FROM schema1.view1 y
GROUP BY y.cid
我的理解是这个查询试图排除“最后一个值”(最后一个日期?) 尝试将其更改为:
SELECT x.cid, x.indt, ROW_NUMBER() OVER( PARTITION BY cid ORDER BY indt DESC ) AS Maxindt
FROM schema1.view1 x
WHERE Maxindt <> 1
尝试将以下索引添加到
rd.ui
表
在 rd.ui(ivid , clior) 上创建索引 idx_PickYourName
按照评论中的建议,请将所有
LIKE
匹配项替换为 =