postgresql 当json键为null时返回Null

bxgwgixi  于 2023-04-20  发布在  PostgreSQL
关注(0)|答案(1)|浏览(214)

我有一个消息表,它有这样的列客户端:
| 身份证|created_by_agent_id|created_by_agent_id|
| --------------|--------------|--------------|
| 1|零|1|
| 二|1|零|
我有一个选择查询,它获取创建它的代理/客户端的消息。

SELECT 
id,
json_build_object(
'id', agent.id,
'firstName', agent.first_name,
) AS "createdByAgent",
json_build_object(
'id', client.id,
'firstName', client.first_name,
) AS "createdByClient"
FROM message 
LEFT JOIN agent
ON message.created_by_agent_id = agent.id
LEFT JOIN client
ON message.created_by_client_id = client.id
WHERE id = 10

问题是,当没有客户端/代理时,生成的json将像这样:

{"id" : null, "firstName" : null, "lastName" : null, "avatarLink" : null}

如何为createdByClient/createdByAgent返回值null

o3imoua4

o3imoua41#

你可以使用CASE ... END在显示数据之前执行IF,如下所示:

SELECT 
id,
CASE
  WHEN agent.first_name is null THEN null
  ELSE json_build_object(
    'id', agent.id,
    'firstName', agent.first_name,
  )
END AS createdByAgent,
CASE
  WHEN client.first_name is null THEN null
  ELSE json_build_object(
    'id', client.id,
    'firstName', client.first_name,
  )
END AS createdByClient
FROM message 
LEFT JOIN agent ON message.created_by_agent_id = agent.id
LEFT JOIN client ON message.created_by_client_id = client.id
WHERE id = 10

显然,您可以向WHEN原因中添加多个参数来检查id是否也为null(例如

相关问题