代碼性能優化-----減小數據庫讀取次數

對於從相同數據源讀取不一樣要求的數據,能夠只讀取一次數據庫,用linq進行數據的分類。數據庫

數據庫示例:優化

--優化前讀取7此數據庫
SELECT COUNT(DISTINCT p) FROM aa WITH(NOLOCK) WHERE DateDiff(dd, c, getdate())=0
SELECT COUNT(DISTINCT p) FROM aa WITH(NOLOCK) WHERE DateDiff(dd, c, getdate())=1
SELECT COUNT(DISTINCT p) FROM aa WITH(NOLOCK)
SELECT SUM(at) FROM aa WITH(NOLOCK) WHERE s=30
SELECT MAX(at) FROM aa WITH(NOLOCK) WHERE s=30
SELECT SUM(at) FROM aa WITH(NOLOCK) WHERE s=10
SELECT SUM(at) FROM aa WITH(NOLOCK) WHERE s=30 and d=1

--優化後讀取一次數據庫
SELECT at,s,d,p,c FROM aa WITH(NOLOCK)

獲取數據示例:spa

       //代碼優化讀7次數據庫,改成讀一次數據庫
            var tempt = RB.GetAA(Config.ConStrRead);
            if (tempt != null&& tempt.Rows.Count>0)
            {
                var enumer = tempt.AsEnumerable();
                var todayPhones= enumer.Where(m => SlConvert.TryToDateTime(m["c"]) >= DateTime.Today).Select(m => SlConvert.TryToInt64(m["Phone"]));
                outModel.TodayRecv = todayPhones.ToList().Distinct().Count();

                //var yesterdayPhones = enumer.Where(m => SlConvert.TryToDateTime(m["c"]) >= DateTime.Today.AddDays(-1)).Select(m => SlConvert.TryToInt64(m["Phone"]));
                //outModel.YesterdayRecv = yesterdayPhones.ToList().Distinct().Count();

                var totalPhones = enumer.Select(m => SlConvert.TryToInt64(m["p"]));
                outModel.TotalRecv = totalPhones.ToList().Distinct().Count();

                var cashed = enumer.Where(m => SlConvert.TryToInt32(m["s"]) == 30).ToList();
                var cashedAfterTaxMoney = cashed.Select(m => SlConvert.TryToInt64(m["at"])).ToList();
                outModel.TotalSaveMoney = cashedAfterTaxMoney.Sum();

                //outModel.ServerMoneyAll = cashed.Where(m => SlConvert.TryToInt32(m["d"]) == 1).Select(m => SlConvert.TryToInt64(m["at"])).Sum();

                outModel.MaxRedBagMoney = cashedAfterTaxMoney.Max();

                outModel.RestRedBagMoney = enumer.Where(m => SlConvert.TryToInt32(m["s"]) == 10).Select(m => SlConvert.TryToInt64(m["at"])).Sum();
            }
相關文章
相關標籤/搜索