递归公用表表达式中的Postgres JSON操作错误

时间:2018-09-26 20:19:42

标签: json postgresql recursive-query

使用此Cte:

WITH RECURSIVE "_.catalogIds" AS (
    SELECT "catalog"."name", "catalog"."parent_id", "catalog"."owner_id", "catalog"."image_id", "catalog"."id", "catalog"."created", "catalog"."updated", "catalog"."icon_class" 
    FROM "catalog" 
    WHERE "catalog"."id" = 1
    UNION 
    SELECT "catalog"."name", "catalog"."parent_id", "catalog"."owner_id", "catalog"."image_id", "catalog"."id", "catalog"."created", "catalog"."updated", "catalog"."icon_class" 
    FROM "_.catalogIds"
    INNER JOIN "catalog" ON "catalog"."id" = "_.catalogIds".parent_id
)

在此表上:

CREATE TABLE catalog (
  id         BIGSERIAL,
  created    timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated    timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  name       JSON      NOT NULL,
  parent_id  BIGINT,
  owner_id   BIGINT    NOT NULL,
  image_id   BIGINT,
  icon_class VARCHAR(255)       DEFAULT 'fa fa-book',

  PRIMARY KEY (id),
  FOREIGN KEY (parent_id) REFERENCES catalog (id) ON DELETE CASCADE,
  FOREIGN KEY (owner_id) REFERENCES "user" (id) ON DELETE CASCADE,
  FOREIGN KEY (image_id) REFERENCES media_file (id) ON DELETE SET NULL
);

导致postgres错误,它找不到json类型的equals运算符。更奇怪的是,它说错误位于语句的选择部分中的位置42。另外,如果我缩短查询,错误会向后移动,因为它停留在查询的特定位置。我写了很多递归查询,但是这看起来很奇怪。在我看来,这似乎是postgres的错误,但我需要确认者和变通/工作示例。

1 个答案:

答案 0 :(得分:1)

UNION消除了重复项,因此查询比较了组件查询的结果行。不幸的是,类型JSON没有相等运算符,因此包含该类型列的行无法进行比较。

您可以在两个查询中将该列强制转换为JSONB

    SELECT "catalog"."name"::jsonb, ...

或如果您不希望重复,则使用UNION ALL