日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
SQL點滴之with語句和子查詢的性能比較

之前筆者和大家分享了《使用with語句來寫一個稍微復(fù)雜sql語句》,這一次筆者針對with語句和子查詢做了一個性能的比較。

成都創(chuàng)新互聯(lián)公司是一家專業(yè)提供梅里斯企業(yè)網(wǎng)站建設(shè),專注與網(wǎng)站建設(shè)、成都網(wǎng)站建設(shè)、H5技術(shù)、小程序制作等業(yè)務(wù)。10年已為梅里斯眾多企業(yè)、政府機構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站設(shè)計公司優(yōu)惠進行中。

在博友SingleCat的提醒下,對with語句做一些性能測試,這里使用的測試工具是SQL Server Profile。我選擇了***一個語句,因為這個語句比較復(fù)雜一點。開始的時候單獨執(zhí)行一次發(fā)現(xiàn)他們的差別不大,就差幾個毫秒,后來想讓他們多執(zhí)行幾次,連續(xù)執(zhí)行10

次看看執(zhí)行的結(jié)果。下面貼出測試用的語句。

 
 
 
 
  1. /*with查詢*/
  2. declare @withquery varchar(5000)
  3. declare @execcount int=0
  4. set @withquery='with TheseEmployees as(
  5. select empid from hr.employees where country=N''USA''),
  6. CharacteristicFunctions as(
  7. select custid,
  8.        case when custid in (select custid from sales.orders as o where o.empid=e.empid) then 1 else 0 end as charfun
  9. from sales.customers as c cross join TheseEmployees as e)
  10. select custid from CharacteristicFunctions group by custid having min(charfun)=1 order by custid
  11. '
  12. while @execcount<10
  13. begin
  14. exec (@withquery);
  15. set @execcount=@execcount+1
  16. end
  17. /*子查詢*/
  18. declare @subquery varchar(5000)
  19. declare @execcount int=0
  20. set @subquery='select custid from Sales.Orders where empid in
  21. (select empid from HR.Employees where country = N''USA'') group by custid
  22. having count(distinct empid)=(select count(*) from HR.Employees where country = N''USA'');
  23. '
  24. while @execcount<10
  25. begin
  26. exec (@subquery);
  27. set @execcount=@execcount+1
  28. end

從SQL Server Profile中截圖如下

從圖中可以看到子查詢語句的執(zhí)行時間要少于with語句,我覺得主要是with查詢中有一個cross join做了笛卡爾積的關(guān)系,于是又實驗了上面的那個簡單一點的,下面是測試語句。

 
 
 
 
  1. /*with語句*/
  2. declare @withquery varchar(5000)
  3. declare @execcount int=0
  4. set @withquery='with c(orderyear,custid) as(
  5. select YEAR(orderdate),custid from sales.orders)
  6. select orderyear,COUNT(distinct(custid)) numCusts from c group by c.orderyear' 
  7. while @execcount<100
  8. begin
  9. exec (@withquery);
  10. set @execcount=@execcount+1
  11. end
  12. /*子查詢*/
  13. declare @subquery varchar(5000)
  14. declare @execcount int=0
  15. set @subquery='select orderyear,COUNT(distinct(custid)) numCusts
  16. from (select YEAR(orderdate),custid from sales.orders) as D(orderyear,custid)
  17. group by orderyear'
  18. while @execcount<100
  19. begin
  20. exec (@subquery);
  21. set @execcount=@execcount+1
  22. end

這次做10次查詢還是沒有多大的差距,with語句用10個duration,子查詢用了11個,有時候還會翻過來。于是把執(zhí)行次數(shù)改成100,這次還是子查詢使用的時間要少,截圖如下

最終結(jié)論,子查詢好比with語句效率高。


當(dāng)前題目:SQL點滴之with語句和子查詢的性能比較
網(wǎng)站路徑:http://m.5511xx.com/article/cdsjoes.html