【问题标题】:Remove unwanted elements from arrays从数组中删除不需要的元素
【发布时间】:2013-10-22 14:20:15
【问题描述】:

我有一张桌子scraped_listings 和一张桌子scraped_categories。列scraped_listings.categories 是一个整数[] 数组,其中包含scraped_categories 中的行ID。

不知何故(可能是由于我不记得犯过的错误),一些 scraped_listings 行的类别中的 id 不属于类别行(我怀疑这些行已被删除)。

我有以下查询,这给了我受影响的行:

SELECT * FROM scraped_listings a
JOIN (
  SELECT array_agg(id) AS ids
  FROM scraped_categories
  ) b ON NOT a.categories <@ b.ids;

我现在想做的是从 categories 中删除此查询找到的行的无效 id - 如果数组中的项目不是有效的 scraped_category id,则应该删除它。

我该怎么做?

【问题讨论】:

  • 可以安全地假设“数组”是指以逗号分隔的整数列表吗?
  • @Dan:是的;我将更新问题以使其更加明确。
  • 对不起,我没有意识到 PostgreSQL 支持实际的数组作为列。
  • As always:请提供表定义和 Postgres 版本。

标签: sql arrays postgresql


【解决方案1】:

Postgres 9.2 或更早版本

UPDATE scraped_listings s
SET   categories = up.categories
FROM (
    SELECT a.pkey, array_agg(a.id) AS categories
    FROM  (
        SELECT pkey, unnest (categories) AS id
        FROM   scraped_listings
        ) a
    JOIN scraped_categories s USING (id) -- eliminates unwanted ids
    ) up
WHERE s.pkey = up.pkey

pkeyscraped_listings的未公开主键列。

在 Postgres 9.3 中,您将使用 LATERAL 来表示相关的 unnest()

UPDATE scraped_listings s
SET   categories = up.categories
FROM (
    SELECT a.pkey, array_agg(a.id) AS categories
    FROM  (
        SELECT pkey, c_id AS id
        FROM   scraped_listings l, unnest(l.categories) c_id  -- implicit LATERAL
        ) a
    JOIN scraped_categories s USING (id) -- eliminates unwanted ids
    ) up
WHERE s.pkey = up.pkey

或者您安装附加模块intarray,它为int[] 提供附加运算符,例如:

int[] - int     int[]   remove entries matching right argument from array

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 2013-06-30
    相关资源
    最近更新 更多