Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to return '1' if a left join returns any rows?

Tags:

sql

join

oracle

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?

like image 682
Paul Tomblin Avatar asked Jul 07 '10 15:07

Paul Tomblin


1 Answers

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;
like image 160
Charles Bretana Avatar answered Sep 17 '22 20:09

Charles Bretana