postgresql 通过嵌套子查询查询视图

nwlls2ji  于 2023-04-20  发布在  PostgreSQL
关注(0)|答案(2)|浏览(190)

你好,有一个v_message视图,看起来像这样

SELECT 
message.id AS "id",
body AS "body",
message.created_at AS "createdAt",
from_phone_number AS "fromPhoneNumber",
to_phone_number AS "toPhoneNumber",
is_read AS "isRead",
json_build_object(
  'id', agent.id,
  'firstName', agent.first_name,
  'lastName', agent.last_name,
  'avatarLink', agent.avatar_link
) AS "createdByAgent",
json_build_object(
  'id', client.id,
  'firstName', client.first_name,
  'displayName', client.display_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查询,如下所示

SELECT * FROM v_message WHERE  v_message."createdByClient".id = 1

但是,我遇到了以下错误:

ERROR:  missing FROM-clause entry for table "createdByClient"
pw9qyyiw

pw9qyyiw1#

必须使用运算符->>以text/varchar的形式获取元素id
由于返回的结果是文本,我们必须使用::integer将其转换为整数,然后将其与integer进行比较:

SELECT * 
FROM v_message 
WHERE  ("createdByClient" ->> 'id')::integer = 1

或者将1转换为varchar:

SELECT * 
FROM v_message 
WHERE  "createdByClient" ->> 'id' = '1'
gcxthw6b

gcxthw6b2#

JSON对象的元素不能用点表示法访问。正确的语法是(v_message."createdByClient" -> 'id')::integer = 1,而不是v_message."createdByClient".id = 1

相关问题