如何从一个空的结果集中返回一个空的json数组。 Postgres 9.5以上

时间:2019-03-06 18:42:11

标签: postgresql

当我在数据库中未找到任何条目但我返回[{}]时,我尝试返回一个空数组[]。我如何只能在空结果集上返回[]?

const getUserProfile = (identifier, value) => {
    return db.oneOrNone (`
    select 
    p.username,
    array_to_json(array_agg(json_strip_nulls(json_build_object('index', pp.index, 'filename', pp.filename)))) as pictures
    from person p
    left join (select person_id, index, filename from person_picture order by index) pp on p.person_id = pp.person_id
    where upper(cast(p.$1~ as text)) = upper(cast($2 as text))
    group by p.person_id`, [ identifier, value ])
}

我尝试:

coalesce(array_to_json(array_agg(json_strip_nulls(json_build_object('index', pp.index, 'filename', pp.filename)))), '[]') as pictures

但它也不起作用。

1 个答案:

答案 0 :(得分:1)

只是一个CASE表达式,用于检查LEFT JOIN的数据是否为空(MAX(pp.index) IS NULL在这种情况下以最小的开销做到了这一点:

SELECT
  p.username, 
  CASE
    WHEN max(pp.index) IS NOT NULL THEN
      array_to_json(array_agg(json_strip_nulls(json_build_object('index', pp.index, 'filename', pp.filename))))
    ELSE
      '[]'::json
  END as pictures
FROM t_person p
LEFT JOIN (SELECT person_id, index, filename FROM t_person_picture ORDER BY index) pp ON p.person_id = pp.person_id
GROUP BY p.username;

完整示例:https://rextester.com/YSNM89392