PostgreSQL 返回包含空值的 JSON 数组

PostgreSQL returning JSON array containing null value

我在 PostgreSQL 上有以下查询,我有显示对象数组的休假列,但有些列没有值并且会 return 空值,但问题是,它总是 return 一个看起来像 [NULL] 的数组,是否可以 return 只有一个空的 []

SELECT 
    u."name",
    u.email,
    to_json(array_agg(row_to_json(uv))) as vacations
from public."user" as u 
join user_address ua on ua.user_id = u.id 
left join user_vacation uv on uv.address_id = ua.id 
where u.place is not null 
group by 
    u."name",
    u.email;

结果:

name       | email            | vacations
some_name  | some@email.com   | [{"id": 1, "area": "description"}]
some_name  | some@email.com   | [{"id": 1, "area": "description"}]
some_name  | some@email.com   | [null]
some_name  | some@email.com   | [null]

您可以count(right-table.column)检查右边table是否有匹配的行;并构建一个 returns [][{...}, {...}] 的 case 表达式,具体取决于计数。

话虽如此,我宁愿re-write你的查询是这样的:

select *, coalesce((
    select json_agg(row_to_json(user_vacation))
    from user_address
    join user_vacation on user_address.id = user_vacation.address_id
    where user_address.user_id = "user".id
), '[]') as vacations
from "user"
where place is not null