首页 > 解决方案 > 如何为使用 jsonb_to_recordset 检索的列设置别名?

问题描述

我有包含对象数组的“电话”列。例如

[
   {
     "id": 8789789789,
     "phone": "111111111",
     "default": true,
     "code": "11",
     "country_code": "US"
   }
]

我需要从这个数组中的一个对象中加入一些值,所以我使用 jsonb_to_recordset 和横向交叉连接

select * 
from "phones" cross join lateral 
     jsonb_to_recordset(phone) as r(phone jsonb, country_code jsonb)
 where "r.country_code" = ? and "deleted_at" is null

这里的问题是检索到的电话(来自对象)用 json 覆盖了初始电话列。如何为连接列设置别名,以便它们不会覆盖原始列?

标签: sqlpostgresqleloquent

解决方案


你可以给他们新的祝福:

select p.*,
       r.phone as r_phone,
       r.r_country_code as r_country_code
from "phones" p cross join lateral 
     jsonb_to_recordset(phone) as r(phone jsonb, country_code jsonb)
 where "country_code" = ? and "deleted_at" is null

推荐阅读