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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With