json - 将查询结果转换为 hstore 时保留列名

标签 json postgresql postgresql-9.1 hstore

我有一个表users,其中包含user_iduser_nameuser_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/

相关文章:

postgresql - 如何将 "1 day 01:30:00"之类的间隔转换为 "25:30:00"?

postgresql - Postgresql 9.1 中 array_agg 的限制

java - 当每个 json 字符串返回不同的变量时,如何高效地将 Json 解析为对象

javascript - 我在这个 javascript 循环操作中做错了什么?

java - 如何在 Android 中解析换行符分隔的 Json 响应?

sql - Postgresql 不使用内存进行缓存

sql - ILIKE 匹配单词边界 PostgreSQL 9

json - Angular $http.get "Uncaught SyntaxError: Unexpected token )"没有文件引用,更别说行号了

python - 创建 PostgreSQL 数据库时遇到问题?

postgresql - 尝试编辑 Postgres 表中的任何单元格时 PhpStorm DB 控制台 View 中出现 "Table is read-only. Search path mismatch"错误