如何在指向另一个 table 的 jsonb 列上使用 ORDER BY 语句 select 来自 Postgres table 的记录
How to select records from a Postgres table using an ORDER BY statement on a jsonb column that points to another table
我有两个 table,characteristics
和 students
。
特征
id name value
---- ------ -------
1 country england
2 country brazil
3 games football
4 games baseball
5 country india
. . .
. . .
学生
first_name age character_values
------------ ----- ------------------
Jason 12 [1,4]
Mark 14 [1,3]
Kunal 10 [5,3]
. . .
. . .
. . .
characteristics
table有三列,其中id
列是自增字段。 name
表示特定特性的名称,value
表示特性的相应信息。
students
table 包含每个学生的详细信息。 students
table 中的 character_value
字段是 jsonb
字段。 jsonb 数组中的每个元素都是一个 ID,指向 characteristics
table.
中适当的特征 ID
(例如,如果学生来自印度国家/地区,则 ID 5 将附加到 character_values
jsonb 数组以对应相应学生的姓名)
假设每个学生只能属于一个国家,我如何select一个学生列表,同时按他们所属国家的名称排序结果?
您可以加入表 jsonb_array_elements
:
select c.*, s.first_name from characteristics c join students s on exists
(select 1 from jsonb_array_elements(s.character_values) v where v.value::int = c.id)
输出:
id
name
value
first_name
1
country
england
Jason
1
country
england
Mark
3
games
football
Mark
3
games
football
Kunal
4
games
baseball
Jason
5
country
india
Kunal
我有两个 table,characteristics
和 students
。
特征
id name value
---- ------ -------
1 country england
2 country brazil
3 games football
4 games baseball
5 country india
. . .
. . .
学生
first_name age character_values
------------ ----- ------------------
Jason 12 [1,4]
Mark 14 [1,3]
Kunal 10 [5,3]
. . .
. . .
. . .
characteristics
table有三列,其中id
列是自增字段。 name
表示特定特性的名称,value
表示特性的相应信息。
students
table 包含每个学生的详细信息。 students
table 中的 character_value
字段是 jsonb
字段。 jsonb 数组中的每个元素都是一个 ID,指向 characteristics
table.
(例如,如果学生来自印度国家/地区,则 ID 5 将附加到 character_values
jsonb 数组以对应相应学生的姓名)
假设每个学生只能属于一个国家,我如何select一个学生列表,同时按他们所属国家的名称排序结果?
您可以加入表 jsonb_array_elements
:
select c.*, s.first_name from characteristics c join students s on exists
(select 1 from jsonb_array_elements(s.character_values) v where v.value::int = c.id)
输出:
id | name | value | first_name |
---|---|---|---|
1 | country | england | Jason |
1 | country | england | Mark |
3 | games | football | Mark |
3 | games | football | Kunal |
4 | games | baseball | Jason |
5 | country | india | Kunal |