Hi have a v_message
view that looks like this
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
I now would like to apply a WHERE
query like so
SELECT * FROM v_message WHERE v_message."createdByClient".id = 1
However I’m presented with the following error:
ERROR: missing FROM-clause entry for table "createdByClient"
2
Answers
Elements of a JSON object aren’t accessed with dot notation. Instead of
v_message."createdByClient".id = 1
, the proper syntax is(v_message."createdByClient" -> 'id')::integer = 1
.The operator
->>
must be used to obtain the elementid
as text/varchar.Since the returned result is text, we must use
::integer
to convert it to an integer before comparing it to aninteger
:OR convert
1
to varchar :