如何在Golang中检索Postgres中第一行JSON的键?

huangapple go评论77阅读模式
英文:

How to retrieve the keys of the json of the first row in postgres in golang?

问题

我目前有一个像这样的表格:

id | value
----------
1  | {"key1":"value1", "test1":"value3"}
2  | {"key1":"value2", "test1":"value4"}

我希望返回的结果是:

key1, test1

每一行中的键都是相同的,但键的数量可能会改变。

我尝试使用以下语句:

SELECT jsonb_object_keys(value) FROM mn_statistics_company

然而,这会返回该行中所有 JSON 的所有键:

key1
test1
key1
test1

我还尝试了以下语句:

SELECT value FROM mn_statistics_company LIMIT 1

但这只返回带有键和值的 JSON:

{"key1":"value1", "test1":"value3"}
英文:

I currently have a table like this

id | value
----------
1  | {"key1":"value1", "test1":"value3"}
2  | {"key1":"value2", "test1":"value4"}

I would like this returned

key1, test1

The keys are the same in each row, but the number of keys may change.

I tired using

SELECT jsonb_object_keys(value) FROM mn_statistics_company

however, that got me all the keys of all the json of that row
key1
test1
key1
test1

and have tired

SELECT value FROM mn_statistics_company LIMIT 1

but that just returns the json with both the key and values.

{"key1":"value1", "test1":"value3"}

答案1

得分: 2

使用SELECT DISTINCT...,例如:

SELECT DISTINCT jsonb_object_keys(value) FROM mn_statistics_company;

SQLFiddle上查看示例。

英文:

Use SELECT DISTINCT..., i.e.

SELECT DISTINCT jsonb_object_keys(value) FROM mn_statistics_company;

See example at SQLFiddle.

huangapple
  • 本文由 发表于 2017年9月10日 06:44:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/46135761.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定