如何解决使用横向连接的查询返回一个带括号的值如何删除它?
我将 Postgres 用于聊天应用程序。我有两张表,一张是对话 ID 和参与者,另一张是消息。
我正在运行以下查询以获取用户的所有对话,并且我使用横向联接将最后一条消息包含在结果中:
select c.id,c.title,c.members,max(m.created_at) delivered_at,last_message
from conversations c
join messages m on c.id = m.conversation_id
left join lateral (select message from messages m where c.id = m.conversation_id order by created_at desc limit 1) last_message on true
where array[4] <@ c.members
group by c.id,last_message
order by delivered_at desc
哪个有效,但消息返回为 (message)
而不是 message
我不知道为什么,真的。有什么我可以做的,这样我就不必将括号替换为附加步骤吗?
解决方法
您需要在选择列表中提及列名,而不是表名或别名:
select c.id,c.title,c.members,max(m.created_at) delivered_at,last_message
from conversations c
join messages m on c.id = m.conversation_id
left join lateral (select message from messages m where c.id = m.conversation_id order by created_at desc limit 1) as t(last_message) on true
where array[4] <@ c.members
group by c.id,last_message
order by delivered_at desc
说明:
在 PostgreSQL 中,查询中对表名(或别名)的引用实际上是对表当前行的复合值的引用。例如,如果我们有一个如上所示的表inventory_item,我们可以这样写:
SELECT c FROM inventory_item c;
此查询生成单个复合值列,因此我们可能会得到如下输出:
c
------------------------
("fuzzy dice",42,1.99)
(1 row)
但是请注意,简单名称与表名称之前的列名称匹配,因此此示例仅适用于查询表中没有名为 c 的列。
普通的qualified-column-name语法table_name.column_name可以理解为对表当前行的复合值应用字段选择。 (出于效率原因,它实际上并未以这种方式实施。)
当我们写
SELECT c.* FROM inventory_item c;
那么,按照SQL标准,我们应该把表的内容展开成单独的列:
name | supplier_id | price
------------+-------------+-------
fuzzy dice | 42 | 1.99
(1 row)
好像查询是
SELECT c.name,c.supplier_id,c.price FROM inventory_item c;
引自以下链接: https://www.postgresql.org/docs/current/rowtypes.html#ROWTYPES-USAGE
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。