当我在数据库中未找到任何条目但我返回[{}]时,我尝试返回一个空数组[]。我如何只能在空结果集上返回[]?
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
但它也不起作用。
答案 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;