Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to avoid group by on a lot of columns

I have two large tables

-Master table A: 1.4million rows
-Detail table B: 9 million rows

B has a foreign key to A.

Basically I need all the 25 detail-fields from table A + in this case a count on B.

Now I have the following pseudo query:

Select
       A.field1,
       A.field2,
       ...
       A.field25,
       Count(b.id)
 from
       A left outer join B on B.fkAid = A.id
 Group by 
       A.id,
       A.field1,
       A.field2,
       ...
       A.field25
Order by A.field1  

The Query plans show the grouping by to take a lot of time (no surprise).

Is there a more efficient way to do this kind of Select?

like image 237
Pleun Avatar asked Mar 30 '11 13:03

Pleun


1 Answers

What about using a common table expression (you tagged it SQL Server 2008?)

WITH CountB AS
(
    SELECT A.aId, value= Count(*)
    FROM A left outer join B on B.fkAid = A.id
    GROUP BY A.id
)
Select
   A.field1,
   A.field2,
   ...
   A.field25,
   CountB.value
from
   A left outer join CountB on A.id = CountB.aId
Order by A.field1  
like image 138
Craig Celeste Avatar answered Oct 29 '22 20:10

Craig Celeste