【问题标题】:Why it works different with ~~ any()?为什么它与 ~~ any() 不同?
【发布时间】:2021-09-24 09:31:43
【问题描述】:

让我先给你看看我的桌子:

INSERT INTO my_table(name, brand, source)
VALUES ('Abc', 'Abc', 'Orig'), 
('Auchan', 'Auchan', 'Orig'), 
('Auchan', 'Auchan', 'Added'),
('dj-auchan-djd', 'Auchan', 'Added'),
('Auchan', 'Other', 'Added'),
('Other', 'oj_auchan', 'Added'),
('Other', 'Other', 'Added');

我想要做的是删除来源为“已添加”且品牌或名称类似于来源为“Orig”的品牌的数据。例如这里我们将删除下一行:

('Auchan', 'Auchan', 'Added'), - simply name and brand is 'Auchan'
('dj-auchan-djd', 'Auchan', 'Added'), - brand ad name has 'Auchan'(but name lowercase)
('Auchan', 'Other', 'Added'), - name is 'Auchan'
('Other', 'oj_auchan', 'Added') - brand has 'Auchan' but lowercase.

那么当我们手动创建这个品牌比较时会是什么:

delete
    from my_table
    where lower(name) ~~ any
           ('{%auchan%,%abc%}') IS TRUE
       or lower(brand) ~~ any
          ('{%auchan%,%abc%}') IS TRUE
       and source = 'Added';

效果很好,我们删除了包含此“欧尚”的所有行。 但是当我试图聚合这些品牌的数组时:

delete
from my_table
where lower(name) ~~ any
      (select '{'||array_to_string(ARRAY_AGG(DISTINCT '%' || lower(brand) || '%'), ',')||'}'
      from my_table
      where source = 'Orig') IS TRUE
   or lower(brand) ~~ any
      (select '{' || array_to_string(ARRAY_AGG(DISTINCT '%' || lower(brand) || '%'), ',') || '}'
      from my_table
      where source = 'Orig') IS TRUE
   and source = 'Added';

不会删除任何数据。

我什至检查了它们是否相似,是的,这两个数组会相似...

有人可以帮忙(或者建议如何删除这些事件)吗?

【问题讨论】:

    标签: postgresql sql-like array-agg


    【解决方案1】:

    问题是子查询的结果被解释为字符串,而不是数组。这是因为这两种形式在语义上是不同的:

    ~~ ANY ('...')  -- will be interpreted as an array literal
    

    ~~ ANY (SELECT ...)  -- will compare with all query results in turn
    

    所以你可以简单地写:

    WHERE lower(name) ~~ ANY
          (SELECT DISTINCT '%' || lower(brand) || '%'
           FROM my_table
           WHERE source = 'Orig')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 2011-10-31
      • 2011-03-15
      • 1970-01-01
      相关资源
      最近更新 更多