我有4张桌子:A,B,C,D。
到目前为止我可以查询:
现在我想在一个select中合并这两个查询,并在那里显示count_b和count_d。但结果选择显示错误计数。以下是我的表现方式:
SELECT
"A"."id",
COUNT("B"."id") AS "B_count",
COUNT("D"."id") AS "D_count"
FROM "users" AS "A" LEFT OUTER JOIN "B" AS "B"
ON "A"."id" = "B"."a__id"
LEFT OUTER JOIN "C" AS "C"
ON "A"."id" = "C"."a_id"
LEFT OUTER JOIN "D" AS "D"
ON "C"."id" = "D"."c_id"
GROUP BY "A"."id"
GROUP BY
可能存在问题。我似乎需要为每个计数单独编写组。我正在寻找没有嵌套选择的结果(因为我仍然需要将它映射到ORM,不要问为什么)。是否可以使用distinct by
进行存档?
答案 0 :(得分:3)
由于您要加入3个表,因此您应该在COUNT中使用DISTINCT:
SELECT
"A"."id",
COUNT(DISTINCT "B"."id") AS "B_count",
COUNT(DISTINCT "D"."id") AS "D_count"
FROM "users" AS "A" LEFT OUTER JOIN "B" AS "B"
ON "A"."id" = "B"."a__id"
LEFT OUTER JOIN "C" AS "C"
ON "A"."id" = "C"."a_id"
LEFT OUTER JOIN "D" AS "D"
ON "C"."id" = "D"."c_id"
GROUP BY "A"."id"