首页 > 解决方案 > 由于加入 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 秒。但在那种情况下,我会让用户休假。

请帮忙,

提前致谢。

标签: sqlsql-serverjoin

解决方案


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;

推荐阅读