从表格中选择首先迭代子集

时间:2016-04-28 06:05:56

标签: sql tsql

我有一个问题:

 select USERNAME, BIRTHDATE, USERID, LASTONLINE, LOCATIONNAME (etc) 
 from [User] 
 where AccountDisabled <> 1 (and a whole bunch of other criteria) 
 order by LastOnline desc offset
 @skip rows fetch next 40 rows only

现在,我已经获得了一个[User] .UserIds列表,该列表在此搜索中具有优先级 - 我们希望首先遍历这些[User],过滤掉符合搜索条件的用户,并返回这些以及匹配的整个[User]表中的下40个。

如何将性能作为优先考虑,如何做到这一点?

1 个答案:

答案 0 :(得分:2)

最简单的解决方案可能是UNION ALL

select USERNAME, BIRTHDATE, USERID, LASTONLINE, LOCATIONNAME (etc) 
 from [User] 
 where AccountDisabled <> 1 (and a whole bunch of other criteria) 
AND USERID IN (list of userids)

UNION ALL

select * from 
 (

    select USERNAME, BIRTHDATE, USERID, LASTONLINE, LOCATIONNAME (etc) 
     from [User] 
     where AccountDisabled <> 1 (and a whole bunch of other criteria) 
    AND USERID NOT IN (list of userids)
     order by LastOnline desc offset
     @skip rows fetch next 40 rows only
 ) as dt

或者你应用一些ROW_NUMBER逻辑:

select *
from
 (
    select USERNAME, BIRTHDATE, USERID, LASTONLINE, LOCATIONNAME (etc),
        CASE WHEN USERID IN (list of userids) THEN 0 ELSE 1 END AS grp
        ROW_NUMBER() 
        OVER (PARTITION BY CASE WHEN USERID IN (list of userids) THEN 0 ELSE 1 END 
              ORDER BY LastOnline desc) AS rn
     from [User] 
     where AccountDisabled <> 1 (and a whole bunch of other criteria) 
 ) as dt
 where grp = 0
    or rn BETWEEN @skip AND @skip + 40