优化SQL查询 - 基于大量排除标准进行选择

时间:2016-05-10 17:44:50

标签: sql stored-procedures database-performance dapper

我正在尝试编写一个查询,该查询捕获符合某些User且存在于子集中的filterCriteria

如果此子集小于numProfilesToFetch,我想捕获该子集中不存在的用户,并附加列表(理想情况下最多为numProfilesToFetch)。

在我的下面的实现中,性能是可怕的(20 + s):

  • 40,000 User s
  • 3,000 topIds
  • 3,000 bottomIds

有没有更有效的方法来解决这个问题?

UserId已编入索引,以及LastOnline

以下执行计划。

 var dapperQuery = "select " + userCols + " from [User]  where " + filterCriteria +
 " AND USERID IN (" + topIds + ") " +
 " AND USERID NOT IN (" + bottomIds + ") " +
 " UNION ALL " +
 " select * from ( " +
 " select " + userCols + " from [User] where " + filterCriteria +
         " AND USERID NOT IN (" + topIds + ") " +
         " AND USERID NOT IN (" + bottomIds + ") " +
         " order by LastOnline asc offset 0 rows fetch next + " +   
         _numProfilesToFetch + " rows only) as dt ";

enter image description here

更新

之前提取了ID列表:

        var idQuery= "select * from [USERSELECTION]  where " +
                         "FROMUSERID = @userId OR TOUSERID = @userId";

        var idResults = connection.Query<UserSelection>(idQuery, new
        {
            userId = userId,
        }).ToList();

        var idArrays = new IdArrays()
        {
            topIds = idResults .Where(s => s.ToUserId == userId && //other stuff).Select(s => s.FromUserId).ToArray(),
            bottomIds = idResults.Where(s => s.FromUserId == userId).Select(s => s.ToUserId).ToArray(),
        };

0 个答案:

没有答案