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?