我有一个表users
,其中包含user_id
、user_name
和user_phone
列。
如果我这样做:
select hstore(u) from users u
结果是:
"user_id" => "1", "user_name" => "McEnroe", "user_phone" => "xxx"
如果我这样做:
select hstore(u) from (select user_id, user_name, user_phone from users) u
结果是:
"f1" => "1", "f2" => "McEnroe", "f3" => "xxx"
我丢失了列的名称。
如何使用第二个示例并拥有正确的列名称?
最佳答案
这是一个缺陷,已在 Postgres 9.2 中修复。
我引用release notes for 9.2 here :
E.5.3.3. Queries
(...)
Retain column names at run time for row expressions (Andrew Dunstan, Tom Lane)
This change allows better results when a row value is converted to hstore or json type: the fields of the resulting value will now have the expected names.
此外,不要使用 user
作为表名,即使它只是一个演示。这是一个reserved word在每个 SQL 标准和 Postgres 中,如果没有双引号,则不能用作表名。我冒昧地修复了Q中的测试用例。
关于json - 将查询结果转换为 hstore 时保留列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18406220/