[英]when use json_agg(json_build_object(.......)) ,how to ensure json_build_object return empty list
As title.如题。 I write some SQL code like below:我写了一些 SQL 代码如下:
SELECT p.id,
json_agg(
json_build_object('id', sp.id)
) AS subProducts
FROM product p
LEFT JOIN sub_product sp
ON sp.product_id = p.id
GROUP BY p.id
as will be observed within正如将在
but i get an issue, whenever product id = 2
, then subProducts
would be [{"id": null}]
但我遇到了一个问题,每当product id = 2
时, subProducts
就是[{"id": null}]
how to i ensure if nothing match, subProducts
to be []
,我如何确保如果没有匹配项, subProducts
是[]
,
i have a idea, add column count(subPrdocts) as childNum,我有一个想法,将列数(subPrdocts)添加为childNum,
and check childNum is 0.并检查 childNum 是否为 0。
But not grace.但不是恩典。
thanks all.谢谢大家。
SELECT p.id,
coalesce(json_agg(
json_build_object('id', sp.id)
) filter (where sp.id is not null ), '[]')AS subProducts
FROM product p
left JOIN sub_product sp
ON sp.product_id = p.id
GROUP BY p.id
filter and coalesce are your friends filter 和 coalesce 是你的朋友
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.