新聞中心
之前筆者和大家分享了《使用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é)果。下面貼出測試用的語句。
- /*with查詢*/
- declare @withquery varchar(5000)
- declare @execcount int=0
- set @withquery='with TheseEmployees as(
- select empid from hr.employees where country=N''USA''),
- CharacteristicFunctions as(
- select custid,
- case when custid in (select custid from sales.orders as o where o.empid=e.empid) then 1 else 0 end as charfun
- from sales.customers as c cross join TheseEmployees as e)
- select custid from CharacteristicFunctions group by custid having min(charfun)=1 order by custid
- '
- while @execcount<10
- begin
- exec (@withquery);
- set @execcount=@execcount+1
- end
- /*子查詢*/
- declare @subquery varchar(5000)
- declare @execcount int=0
- set @subquery='select custid from Sales.Orders where empid in
- (select empid from HR.Employees where country = N''USA'') group by custid
- having count(distinct empid)=(select count(*) from HR.Employees where country = N''USA'');
- '
- while @execcount<10
- begin
- exec (@subquery);
- set @execcount=@execcount+1
- end
從SQL Server Profile中截圖如下
從圖中可以看到子查詢語句的執(zhí)行時間要少于with語句,我覺得主要是with查詢中有一個cross join做了笛卡爾積的關(guān)系,于是又實驗了上面的那個簡單一點的,下面是測試語句。
- /*with語句*/
- declare @withquery varchar(5000)
- declare @execcount int=0
- set @withquery='with c(orderyear,custid) as(
- select YEAR(orderdate),custid from sales.orders)
- select orderyear,COUNT(distinct(custid)) numCusts from c group by c.orderyear'
- while @execcount<100
- begin
- exec (@withquery);
- set @execcount=@execcount+1
- end
- /*子查詢*/
- declare @subquery varchar(5000)
- declare @execcount int=0
- set @subquery='select orderyear,COUNT(distinct(custid)) numCusts
- from (select YEAR(orderdate),custid from sales.orders) as D(orderyear,custid)
- group by orderyear'
- while @execcount<100
- begin
- exec (@subquery);
- set @execcount=@execcount+1
- end
這次做10次查詢還是沒有多大的差距,with語句用10個duration,子查詢用了11個,有時候還會翻過來。于是把執(zhí)行次數(shù)改成100,這次還是子查詢使用的時間要少,截圖如下
最終結(jié)論,子查詢好比with語句效率高。
當(dāng)前題目:SQL點滴之with語句和子查詢的性能比較
網(wǎng)站路徑:http://m.5511xx.com/article/cdsjoes.html


咨詢
建站咨詢
