【问题标题】:Optimizing Linq Query to minmal fetching time?将 Linq 查询优化到最短的获取时间?
【发布时间】:2021-03-04 15:48:42
【问题描述】:

我有嵌套条件运算符 Linq 查询来获取记录。问题是我在每个条件数据库上编写了多个 select&join,命中时间太高而无法获取记录,我需要减少查询命中 db 的时间。

由于我是 Enity Framwork 的新手,所以我没有太多优化使用条件语句的方式。

var uniqID = 12;
var keyID = 439;

var result = (from t1 in Table1
where t1.uniqueID == uniqID && t1.column9 == keyID && t1.column11 == true
select new {
  Data1 = t1.Column1,
  Data2 = t1.Column2,
  Data3 = t1.Column3 == true ? (from t2 in Table2
  where t2.uniqueID == uniqID && t2.Id == t1.column10
  select t2.Data4).FirstOrDefault() : (from t3 in Table3
  join t4 in Table4 on new {
    t3.uniqueID,
    t3.coulmn6
  }
  equals new {
    t4.uniqueID,
    t4.coulmn6
  }
  where t3.uniqueID == uniqID && t3.keyID == t1.column10
  select t4.Data4).FirstOrDefault(),
  ReceiptNo = (from t3 in Table3
  join t5 in Table5 on new {
    t3.uniqueID,
    t3.coulmn6
  }
  equals new {
    t5.uniqueID,
    t5.coulmn6
  }
  where t3.uniqueID == uniqID && t3.keyID == t1.column9
  select t5.Data5).FirstOrDefault()
}).Dump();

这是一个类似的。像这样我必须添加几个(比如 4-5)更多的子查询以及上面的一个

【问题讨论】:

标签: sql entity-framework linq linq-to-entities


【解决方案1】:

我希望它会被英孚翻译。想法是对两个子查询进行 OUTER APPLY。

var uniqID = 12;
var keyID = 439;

var query = 
   from t1 in Table1
   where t1.uniqueID == uniqID && t1.column9 == keyID && t1.column11 == true
   from t2Data in Table2.Where(t2 => t2.uniqueID == uniqID && t2.Id == t1.column10)
      .Select(x => x.Data4).Take(1).DefaultIfEmpty()
   from t3Data in (
      from t3 in Table3
      join t4 in Table4 on new {
         t3.uniqueID,
         t3.coulmn6
      }
      equals new {
         t4.uniqueID,
         t4.coulmn6
      }
      where t3.uniqueID == uniqID && t3.keyID == t1.column10
      select t4.Data4).Take(1).DefaultIfEmpty()

   select new {
      Data1 = t1.Column1,
      Data2 = t1.Column2,
      Data3 = t1.Column3 == true ? t2Data : t3Data
   };

query.Dump();

【讨论】:

    猜你喜欢
    • 2018-11-06
    • 2022-06-14
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多