在Postgres中加入两个表后如何为具有相同名称的列提供别名
Posted
技术标签:
【中文标题】在Postgres中加入两个表后如何为具有相同名称的列提供别名【英文标题】:How to give alias for columns with same name after joining two tables in Postgres 【发布时间】:2021-05-13 23:21:13 【问题描述】:大家好,我正在对两个表进行内部连接,并从两个表中选择所有列。但是我得到了三个同名的列,例如 id、created_at 和 updated_at。
查询:
SELECT addresses.* , facilities.* FROM facilities
INNER JOIN addresses
ON facilities.main_address_id = addresses.id
在选择所有带有 * 的列时,有什么可能的方法可以为上述具有相同名称的列提及别名?
任何形式的帮助将不胜感激!谢谢!
【问题讨论】:
不,没有自动重命名列的方法。相关(如果不重复):***.com/questions/5179648 【参考方案1】:不,除了分别为每列设置别名之外,您不能这样做。
但如果您的查询是重复的,您可以创建 VIEW:
CREATE OR REPLACE VIEW facilities_addresses AS
SELECT
addresses.column AS "addresses_column",
facilities.column AS "facilities_column"
FROM facilities
INNER JOIN addresses ON (facilities.main_address_id = addresses.id)
然后就可以查询了:
SELECT * FROM facilities_addresses
【讨论】:
【参考方案2】:是的,你可以
SELECT
addr.id as addressesId ,
addr.created_at as addresses_created_at,
addr.updated_at as addresses_update_at,
fac.id as facilitiesId,
fac.created_at as facilities_created_at,
fac.updated_at as facilities_updated_at FROM facilities as fac
INNER JOIN addresses as addr
ON facilities.main_address_id = addresses.id
【讨论】:
是的,必须提到查询中的所有列名以上是关于在Postgres中加入两个表后如何为具有相同名称的列提供别名的主要内容,如果未能解决你的问题,请参考以下文章