是否有更有效的方法来编写此SQL查询?
它在大约45秒内从一组100,000行中返回大约800行。
我使用的是Sql Server 2008 R2
Select a.Div as Division
,a.Room as RoomLocation
,a.Form as Forms
,a.Nums as TotalNumberLocations
From AView a
Where a.Id = '1'
And a.Div = 'A'
Group By a.Div, a.Nums, a.Room, a.Form
union
Select b.Div as Division
,b.Room as RoomLocation
,b.Form as Forms
,b.Nums as TotalNumberLocations
From AView b
Where b.Id = '1'
And b.Div = 'G'
Group By b.Div, b.Nums, b.Room, b.Form
union
Select c.Div as Division
,c.Room as RoomLocation
,c.Form as Forms
,c.Nums as TotalNumberLocations
From AView c
Where c.Id = '1'
And c.Div = 'R'
Group By c.Div, c.Nums, c.Room, c.Form
Order By Forms asc, TotalNumberLocations asc
答案 0 :(得分:7)
为什么在IN子句中拥有值时可以使用UNION?你正在扫描桌子三次。
Select Div as Division
,Room as RoomLocation
,Form as Forms
,Nums as TotalNumberLocations
From AView
Where Id = '1'
And Div IN ('A','G','R')
Group By Div, Nums, Room, Form
Order By Forms asc, TotalNumberLocations asc
答案 1 :(得分:4)
与the other answer类似,但您也可以将GROUP BY
替换为distinct
Select distinct Div as Division
,Room as RoomLocation
,Form as Forms
,Nums as TotalNumberLocations
From AView a
Where Id = '1'
And Div in ('A', 'G', 'R')
Order By Forms asc, TotalNumberLocations asc
答案 2 :(得分:2)
我认为表Id
的列Div
和AView
的索引对于此查询的性能非常有用,可能更多的是重写查询。