postgresql 如何从postgres中的值Map引用jsonb列值

gojuced7  于 2023-01-17  发布在  PostgreSQL
关注(0)|答案(1)|浏览(125)

我希望能够根据err_map jsonb列的结果表中的err_id引用消息和描述的错误表,我还希望能够关联哪个列发生了哪个错误(独立的columns c1,c2val_map jsonb column c3, c4
这是X1 M4 N1 X将数据(具有X1 M5 N1 X)存储为X1 M6 N1 X的唯一原因,因此当将错误Map到列时,我们可以识别这些列来自X1 M7 N1 X。
这里有一个结果表,err_map列值1,3引用了下面的错误表

id    |   c1    |  c2     | val_map              | err_map
----------------------------------------------------------------
    1    |   chk1  |  chk2   | {"c3":3, "c4":4}     | {"c1": 1, "val_map.c3": 3}

错误表

id    |   msg   |  description
----------------------------------------------------------------
    1    |   msg1  |  an error1 occurred
----------------------------------------------------------------
    3    |   msg3  |  an error3 occurred

我看了jsonb_eachjsonb_object_keys,但是不能真正弄清楚如何使用它来连接这些表。任何帮助/提示将不胜感激。如果有不清楚的地方,请原谅,请要求提供更多的细节。
[Edit 1]:删除了外键引用,因为它具有误导性
[Edit我已经让它工作了,但是效率很低

select
  e.error_key,
  e.error_message,
  T2.key as key
from result.error e
inner join (
  select
    substring(T1.key, 11) as key,
    T1.value
  from (
    select em.key, em.value
    from result rd, jsonb_each(rd.error_map) as em
  ) as T1
  where T1.key like '%value_map%'
union all
  select T1.key , T1.value
  from (
    select em.key, em.value
    from result rd, jsonb_each(rd.error_map) as em
  ) as T1
  where T1.key not like '%value_map%'
) as T2 on T2.value::bigint = e.id;
q5lcpyga

q5lcpyga1#

你可以把UNION ALL简化为

select
  e.error_key,
  e.error_message,
  T2.key as key
from result.error e
inner join (
  select
    case when T1.key like 'val_map.%'
      then substring(T1.key, 9)
      else T1.key
    end as key,
    T1.value
  from result rd, jsonb_each(rd.error_map) as T1
) as T2 on T2.value::bigint = e.id;

相关问题