我有三张桌子,’A’,’B’和’C’.我查询了’A’和’B’,但是我想添加一个字段,告诉我是否有一个或多个(我不关心多少)’C’是外来键入’A’.
这就是我所拥有的:
- 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_4
- ORDER BY CASE WHEN A.col_2 = ?
- THEN 0
- ELSE 1
- END,col_3;
这似乎有点低效,因为我必须在GROUP BY中列出所有这些字段,也因为我正在计算我真正想要的是否至少有一个匹配.这可以改善吗?
解决方法
使用子查询存在而不是……
- Select A.A_id,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;