sql - 由于加入 SQL 导致的性能问题
问题描述
我在使用左连接(3 分钟)时需要更多时间来获取数据。但是当尝试使用内部连接时,它只需要不到 20 秒。由于内部连接消除了相应表中没有数据的其他记录,因此我无法获取所有记录。请帮助解决这个问题。
询问:
SELECT UserName, UserEmail, UserLeaveReason FROM [dbo].[UserData] UD WITH (NOLOCK)
INNER JOIN #vw_User REQ on UD.UserID= REQ.UserID
LEFT JOIN Txn_UserLeaveDetails TD ON TD.RELREQID = REQ.RELREQID AND TD.IsActive = 1
LEFT JOIN MST_LeaveDescription TS ON TS.LeaveDescriptionId = TD.LeaveDescriptionId
Txn_UserLeaveDetails :包含用户的休假详细信息,可以是活动的和不活动的(过去的离开)。对于这个查询,我只需要当前叶子的数据。
**Txn_UserLeaveDetails**
RELREQID
UserID
LeaveStartDate
LeaveEndDate
CreatedDate
CreatedBy
UpdatedDate
UpdatedBy
IsActive
MST_LeaveDescription :该表给出了休假原因的描述。
**MST_LeaveDescription**
LeaveDescriptionId
LeaveReason
CreatedDate
UpdateDate
在上面的查询输出中,我需要所有用户数据,无论他们的休假状态如何。但是使用上述查询需要 3 分钟。但是,当我将加入与 MST_LeaveDescription 更改为内部加入时,它只需要 20 秒。但在那种情况下,我会让用户休假。
请帮忙,
提前致谢。
解决方案
create table #UserLeave
(
UserId int index idxUserId,
UserLeaveReason varchar(200)
)
--get active leaves
insert into #UserActiveLeave(UserId, UserLeaveReason)
select TD.UserID, TS.LeaveReason
from Txn_UserLeaveDetails TD
join MST_LeaveDescription TS on TD.LeaveDescriptionId = TS.LeaveDescriptionId
where TD.IsActive = 1;
--get the rest of the users without active leaves
insert into #UserActiveLeave(UserId)
select UserID
from [dbo].[UserData]
except
select UserId
from #UserActiveLeave;
--result
select ud.UserName, ud.UserEmail, ua.UserLeaveReason
from #UserActiveLeave as ua
join [dbo].[UserData] as ud on ua.UserId = ud.UserId;
推荐阅读
- django - 为什么 Django REST Framework (DRF) 文件夹结构与 Django Turorial 不同?
- javascript - 在 monaco 编辑器中添加内联小部件
- powerpoint - python-pptx中包含文本的圆圈
- visual-studio - 在 Visual Studio 中重新映射符号(如在 AutoHotkey 中)
- strava - Strava API - 如何为上传的活动设置活动类型?
- getstream-io - 是否可以在 getStream.io 中实现独立的通知提要?
- twilio - 使用 Twilio 的客户端到客户端 VoIP 语音 SDK 呼叫
- javascript - 我可以直接通过azure中的clientId等url片段获取令牌吗?
- docker-compose - 如果我在 Docker Compose 中使用“restart: always”运行 node.js 应用程序,我还需要像 PM2 这样的进程管理器吗?
- fastapi - python fastapi:我想得到一个csv文件作为回报