Ø  简介

在平常的开发中,我们经常会编写各种各样的 SQL 语句,比如:SQL 查询、存储过程、或者视图查询等。当我们编写的 SQL 语句比较复杂,或者表的数据量比较大,导致查询超时!这时,就要去分析我们的 SQL 语句,导致耗时较长的原因,从而优化我们的 SQL 语句。

说明:本文仅为笔者所思、所想、所写,有用之处欢迎借鉴,不对之处欢迎指出。

1.   内连接查询中,子查询(关联相同的两张表)使用 TOP 子句解决耗时

1)   LINQ 语句

var datas = (from t1 in DataContext.Orders

join t3 in DataContext.UserInfoes on t1.UserId equals t3.id

join t5 in DataContext.Customers on t3.CustomerId equals t5.Id

join t7 in (from t1 in DataContext.CateringCategorys

join t3 in DataContext.CateringCategorys on t1.CategoryId equals t3.ParentId

where t1.Level == 1

select new

{

CategoryId1 = t1.CategoryId,

CategoryId2 = t3.CategoryId

}) on t5.TradeType equals t7.CategoryId2

where 1 == 1

&& (cityId == 0 || t1.CityId == strCityId)

&& t1.OrderStatusId >= (int)OrderStates.Undelivered && t1.OrderStatusId < (int)OrderStates.Cancelled

&& t1.PayStatusId != (int)OrderPayStates.Unpaid

&& (t1.PayTime >= startDate && t1.PayTime < endDate)

select new

{

CategoryId = t7.CategoryId1,

OrderId = t1.Id,

t1.RealTotal,

t3.CustomerId

}).ToArray();

2)   生成 SQL(sp_executesql 转换后的同等 SQL 语句)

SELECT

记录。

2)   在关联的第二个 Crm_CateringCategory 表上再派生一层,再关联外层 Crm_CateringCategory 表,并只输出所需字段?结果还是不行!

3)   因为关联的是相同的表?对的,就是这个原因!因为,尝试创建与 CateringCategory 相同的另一张表 CateringCategory_1 去关联查询,耗时问题就解决了。

4)   为什么呢,表上加 (NOLOCK) 关键字也不管用,原因不祥(如有博友们知道,欢迎指出)!

4.   然后,笔者又尝试在这个子查询上加上 TOP 子句,结果执行耗时变为了 00:00:00.740,耗时问题同样解决了。因为开发中,不可能再去创建一张相同的一张表。(Linq 只需加上 Take() 方法即可)。

最新文章

  1. Memcached和Memcache安装(64位win7)
  2. SLF4J的好处
  3. for循环嵌套
  4. Java关键字:transient,strictfp和volatile简介
  5. SqlDataReader执行带输出参数存储过程 错误分析
  6. Codeforces Round #209 (Div. 2)C
  7. lintcode:搜索二维矩阵II
  8. 拓展,Fibonacci螺旋
  9. Call Azure Queue get &quot;The remote server returned an error: (400) Bad Request.&quot;
  10. 移动App Crash的测试用例设计
  11. JDBC获取数据库Connection的工具抽取
  12. 高级软件工程2017第6次作业--团队项目:Alpha阶段综合报告
  13. ubuntu安装docker-ce
  14. 拷贝文件到服务器 提示FTP文件夹错误
  15. Qt的事件
  16. 常用的shell脚本(安全方向)
  17. RequestDispatcher.forward转发与HttpServletResponse.sendRedirect重定向
  18. 【CF908E】New Year and Entity Enumeration 位运算+DP
  19. win7 任务计划运行批处理,不能正常运行,需用绝对路径
  20. redis与ssm整合(用 redis 替代mybatis二级缓存)

热门文章

  1. oracle sql developer 出现 : 适配器无法建立连接问题解决方案 The Network Adapter could not establish the connection
  2. 记一次zabbix排错(数据库安装在其它服务器上)
  3. 做优化的数据库工程师请参考!CynosDB的计算层设计优化揭秘
  4. Linux学习历程——Centos 7 账户管理命令(用户篇)useradd usermod userdel
  5. jQuery列表选择美化插件uichoose
  6. 光盘安装win7系统教程
  7. Springboot整合Kfka
  8. HP LasterJet 3050驱动安装技巧,面向win7,8,8.1,10
  9. 类Scanner
  10. keras04 GAN simple