我在包含75万个条目的表上运行查询时出现性能问题。执行需要15到20秒,在此期间阻止访问数据库并创建大量错误日志(当然还有愤怒的客户)。
以下是查询:
DECLARE @FROM_ID AS UNIQUEIDENTIFIER = 'XXX'
DECLARE @TO_ID AS UNIQUEIDENTIFIER = 'YYY'
update tbl_share
set user_id = @TO_ID
where user_id = @FROM_ID
and not exists (
select *
from tbl_share ts
where ts.file_id = file_id
and ts.user_id = @TO_ID
and ts.corr_id = corr_id
and ts.local_group_id = local_group_id
and ts.global_group_id = global_group_id
)
由于我的TSQL知识有限,我现在有点卡住了。 我想知道是否:
我没有很多机会运行测试,因为它是一个生产数据库,并且每天都有10-20个客户连接。
感谢您的帮助!
答案 0 :(得分:0)
重构代码逻辑怎么样?
DECLARE @FROM_ID AS UNIQUEIDENTIFIER = 'XXX'
DECLARE @TO_ID AS UNIQUEIDENTIFIER = 'YYY'
IF NOT EXISTS (select *
from tbl_share ts
where ts.user_id = @TO_ID)
BEGIN
update tbl_share
set user_id = @TO_ID
where user_id = @FROM_ID
END
因此,您事先正在进行检查,并且只在需要时才更新数据库。
HTH
答案 1 :(得分:0)
让我们从优化选择开始 检查查询计划 如果这是PK,那么它是否支离破碎?
select *
from tbl_share
where user_id = @FROM_ID
and not exists (
select *
from tbl_share ts
where ts.file_id = file_id
and ts.user_id = @TO_ID
and ts.corr_id = corr_id
and ts.local_group_id = local_group_id
and ts.global_group_id = global_group_id
)
select tUpdate.*
from tbl_share as tUpdate
left outer join tbl_share as tExists
on tUpdate.user_id = @FROM_ID
and tExists.user_id = @TO_ID
and tExists.file_id = tUpdate.file_id
and tExists.corr_id = tUpdate.corr_id
and tExists.local_group_id = tUpdate.local_group_id
and tExists.global_group_id = tUpdate.global_group_id
where tExists.user_id is null