tags:

views:

80

answers:

1

I have three tables, 'A', 'B' and 'C'. I have query on 'A' and 'B', but I want to add a field that tells me whether or not there is one or more (I dont' care how many) 'C' that are foreign keyed to 'A'.

Here's what I have:

SELECT    A.A_id, A.col_2, col_3, B.col_2, A.col_4
          count(C.id) as C_count
FROM      A
JOIN      B ON (A.B_id = B.B_id)
LEFT JOIN C ON (A.A_id = C.A_id)
WHERE     A.A_id = ?
GROUP BY  A.A_id, A.col_2, col_3, B.col_2, A.col_4
ORDER BY  CASE WHEN A.col_2 = ?
               THEN 0
               ELSE 1 
          END, col_3;

It seems a little inefficient, both because I have to list all those fields in the GROUP BY and also because I'm counting where all I really want is whether there is at least one match or not. Can this be improved?

+13  A: 

use Exists with a subquery instead...

 Select A.A_id, A.col_2, col_3, 
    B.col_2, A.col_4, 
    Case When Exists (Select * From C
                      Where A_id = A.A_id)
         Then 1 Else 0 End As C_Exists
 From A Join B 
     On (A.B_id = B.B_id) 
 Where A.A_id = ?    
 Order By Case When A.col_2 = ? 
           Then 0 Else 1 End, col_3;
Charles Bretana
+1 for exists :-)
glowcoder
Excellent. EXPLAIN PLAN says it's better, too. 3 minutes until I can accept it.
Paul Tomblin
@Paul Tomblin: That's because EXISTS will return true as soon as the first successful match to the criteria is found - there's no need for EXISTS to check of all matching criteria.
OMG Ponies