【问题标题】:Nested loop over selected row_to_json result在选定的 row_to_json 结果上嵌套循环
【发布时间】:2021-11-16 16:31:36
【问题描述】:

我正在尝试对 row_to_json() 的结果进行嵌套循环,但出现错误。

DO
$BODY$
DECLARE
    js jsonb := '{"ddd525b9-e47c-46ac-ab55-e0db93338ff3": "ddd525b9-e47c-46ac-ab55-e0db93338ff4", "550e8400-e29b-41d4-a716-446655440000": "e15c6fe3-000c-4c69-9c41-9e241323cbe5", "0ba26163-bf75-40d2-8526-172229604d95": "7ed83dbc-3895-490c-8a16-9842cfe85e28"}';
    i record;
BEGIN
  FOR i IN SELECT * FROM jsonb_each_text(js)
  loop
    DECLARE
    orgs jsonb := (SELECT row_to_json(t) FROM (Select parent_id from my_schema.my_table o where o.id != i.value) t);
    j record;
    for j in select * from jsonb_each_text(orgs)
    loop
      RAISE NOTICE 'key %', j.key;
      RAISE NOTICE 'value %', j.value;
    end loop;
  END LOOP;
END;
$BODY$;

错误:

SQL Error [42601]: ERROR: syntax error at or near "for"
  Position: 506

【问题讨论】:

    标签: sql postgresql psql


    【解决方案1】:

    您在第二个循环中忘记了 BEGIN 和 END。

    DO
    $do$
    DECLARE
        js jsonb := '{"ddd525b9-e47c-46ac-ab55-e0db93338ff3": "ddd525b9-e47c-46ac-ab55-e0db93338ff4", "550e8400-e29b-41d4-a716-446655440000": "e15c6fe3-000c-4c69-9c41-9e241323cbe5", "0ba26163-bf75-40d2-8526-172229604d95": "7ed83dbc-3895-490c-8a16-9842cfe85e28"}';
        i record;
    BEGIN
      FOR i IN (SELECT * FROM jsonb_each_text(js)) LOOP
        DECLARE
          orgs jsonb := (SELECT row_to_json(t) FROM (Select parent_id from my_schema.my_table o where o.id != i.value) t);
          j record;
        BEGIN
          FOR j IN (select * from jsonb_each_text(orgs)) LOOP
            RAISE NOTICE 'key %', j.key;
            RAISE NOTICE 'value %', j.value;
          END LOOP;
        END;
      END LOOP;
    END;
    $do$;
    

    【讨论】:

    • 谢谢,但现在收到此错误:SQL Error [42883]: ERROR: operator does not exist: uuid <> text Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
    • 您需要将 jsonb (i) 结果转换为uuid。在您的示例中,您使用 where o.id != i.value 将其更改为 where o.id != i.value::uuid。
    • 是的,我使用了uuid(i.value),它也很有效。现在它说,SQL Error [21000]: ERROR: more than one row returned by a subquery used as an expression
    • row_to_json 期望一行,所以结果 Select parent_id from my_schema.my_table o where o.id != uuid(i.value) 应该只有 1 行。但我认为你想要所有的组织,在这种情况下你可以JSONB_AGG(parent_id) 而不是row_to_json
    猜你喜欢
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多