首页 > 解决方案 > 使用模式时,Postgresql ILIKE/LIKE ANY 不返回任何结果

问题描述

我在 PostgreSQL 数据库(版本 12.1)中有一个表(食物),它有一个名为 common_names 的列,它是一个文本数组(TEXT [])。在数据中,术语“家庭风格”在数据库中的 common_names 条目中出现了 35 次。

以下 3 个查询均返回值“35”:

select count(1) from foods where 'family style' = ANY (common_names);

select count(1) from foods where 'family style' LIKE ANY (common_names);

select count(1) from foods where 'FAMILY STYLE' ILIKE ANY (common_names);

以下所有查询都返回零 (0):

select count(1) from foods where '%family%' LIKE ANY (common_names);

select count(1) from foods where '%family%' ILIKE ANY (common_names);

select count(1) from foods where 'family%' LIKE ANY (common_names);

select count(1) from foods where 'FAMILY%' ILIKE ANY (common_names);

我究竟做错了什么?

标签: sqlpostgresql

解决方案


好的,在我的一位同事的帮助下,我们能够解决这个问题。

因此,对于初学者来说,您似乎无法将 LIKE 或 ILIKE 与数组列一起使用 - 您可以,只是无法正常工作。似乎只能使用完全匹配。

但是,您可以取消嵌套数组以进行搜索。

这是最终起作用的查询:

SELECT COUNT(1) FROM (
    SELECT global_id, common_names FROM foods,
        LATERAL unnest(common_names) AS common_names(common_name)
    WHERE common_name LIKE '%family%'
    GROUP BY global_id, common_names) AS X;

推荐阅读