【问题标题】:How to select records from a Postgres table using an ORDER BY statement on a jsonb column that points to another table如何在指向另一个表的 jsonb 列上使用 ORDER BY 语句从 Postgres 表中选择记录
【发布时间】:2021-12-31 13:48:09
【问题描述】:

我有两张桌子,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 表有三列,其中id 列是自动递增字段。 name 表示特定特征的名称,value 表示有关该特征的各自信息。

students 表包含每个学生的详细信息。 students 表中的character_value 字段是jsonb 字段。 jsonb 数组中的每个元素都是一个 ID,指向 characteristics 表中相应的特征 ID。

(例如,如果学生来自印度,则 ID 5 将附加到character_values jsonb 数组中对应学生的姓名)

假设每个学生只能属于一个国家,我如何选择一个学生列表,同时按照他们所属国家的名称排序结果?

【问题讨论】:

    标签: sql database postgresql sql-order-by jsonb


    【解决方案1】:

    您可以通过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

    【讨论】:

    • 您为什么使用 SELECT 1 而不是 SELECT *?有什么具体原因吗?
    • @Vinay select 1 是 exists 子查询的约定。
    猜你喜欢
    • 2016-06-23
    • 2014-09-17
    • 2018-05-22
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多