【问题标题】:Trying to join on set returning function尝试加入集合返回功能
【发布时间】:2022-01-11 19:49:04
【问题描述】:

我正在尝试使用从其中一个表的 json 数组中提取的 ID 加入两个表,我发现了一些关于横向连接的主题,但我无法理解,我无法在我的案例中实现它。 或者也许还有其他方法可以做到这一点?

create table jsontable (response jsonb);
insert into jsontable values ('{"SCS":[{"customerId": 100, "referenceId": 215}, {"customerId": 120, "referenceId":544}, {"customerId": 400, "referenceId": 177}]}');

create table message (msg_id integer, status integer, content text);
insert into message values
(544, 1, 'Test'), (134, 1, 'Test2'), (177, 0, 'Test3'), (215, 1, 'Test4');

SELECT m.*
FROM jsontable t
JOIN message m ON m.msg_id = (jsonb_array_elements(t.response -> 'SCS')->>'referenceId')::int
and m.status = 1 

https://dbfiddle.uk/?rdbms=postgres_12&fiddle=8b3890efd34199f2356b6abca2f811c2

当然它会抛出一个错误:在 JOIN 条件中不允许设置返回函数

【问题讨论】:

  • JOIN message m ON m.msg_id IN (SELECT (jsonb_array_elements(t.response -> 'SCS')->>'referenceId')::int)

标签: json postgresql


【解决方案1】:

看起来您想要加入的是数组中的单个对象,而不是整行。所以使用

SELECT m.*, obj
FROM jsontable t, jsonb_array_elements(t.response -> 'SCS') obj
JOIN message m ON m.msg_id = (obj->>'referenceId')::int AND m.status = 1;

或者(更易读的imo)

SELECT m.*, obj
FROM jsontable t,
LATERAL jsonb_array_elements(t.response -> 'SCS') obj
JOIN message m ON m.msg_id = (obj->>'referenceId')::int
WHERE m.status = 1;

(updated fiddle)

【讨论】:

  • 是否可以将另一个表内部连接到 jsontable t 等等?因为当我尝试时,它会抛出一个错误“表“t”有一个条目,但不能从这部分查询中引用它。”,如何欺骗它?
  • @sh4rkyy 您可能希望 ask a new question 处理失败的查询。一般来说,这听起来像是一个优先级或嵌套问题。
【解决方案2】:

jsonb_array_elements() :: int 返回一组整数,不能等于一个整数m.msg_id

试试吧:

SELECT m.*
FROM jsontable t
JOIN message m ON m.msg_id IN (SELECT (jsonb_array_elements(t.response -> 'SCS')->>'referenceId')::int)
and m.status = 1 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    相关资源
    最近更新 更多