0

有没有更有效的方法来编写这个 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
4

3 回答 3

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
于 2013-09-06T19:08:04.273 回答
4

其他答案类似,但是您也可以GROUP BYdistinct

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
于 2013-09-06T19:10:08.500 回答
2

我会假设列IdDiv表上的索引对AView这个查询的性能非常有益,可能比重写查询要多得多。

于 2013-09-06T19:16:51.363 回答