联合子查询左联接-太慢

时间:2020-11-11 09:13:39

标签: sql-server union

此查询永远不会完成...

select u.anUserId, u.acUserId, u.acTitle, u.acActive, activeUsers365.* 
from tPA_User u
    left join (

        select distinct u.anuserid, u.acUserId, u.acTitle
        from the_moveitem mi
            left join tpa_user u on u.anUserId = mi.anUserIns
        where mi.adTimeIns > getdate() - 365

        union

        select distinct u.anuserid, u.acUserId, u.acTitle
        from the_moveitem mi
            left join tpa_user u on u.anUserId = mi.anUserChg
        where mi.adTimeIns > getdate() - 365

    ) activeUsers365 on activeUsers365.anUserId = u.anUserId

此人立即执行...(不使用工会)

select u.anUserId, u.acUserId, u.acTitle, u.acActive, activeUsers365.* 
from tPA_User u
    left join (

        select distinct u.anuserid, u.acUserId, u.acTitle
        from the_moveitem mi
            left join tpa_user u on u.anUserId = mi.anUserIns
        where mi.adTimeIns > getdate() - 365

    ) activeUsers365 on activeUsers365.anUserId = u.anUserId

我该怎么做?我想离开两个子查询的联合,而不是让他们自己加入。

1 个答案:

答案 0 :(得分:0)

删除子查询左联接,因为它们是多余的。

问题不是工会,而是联接。

select u.anUserId, u.acUserId, u.acTitle, u.acActive, activeUsers365.* 
from tPA_User u
    left join (

        select mi.anUserIns userId
        from the_moveitem mi
        where mi.adTimeIns > getdate() - 365

        union

        select mi.anUserChg userId
        from the_moveitem mi
        where mi.adTimeIns > getdate() - 365

    ) activeUsers365 on activeUsers365.userId = u.anUserId