Postgres Query of an Array using LIKE

前端 未结 2 1615
梦如初夏
梦如初夏 2020-12-11 01:07

I am querying a database in Postgres using psql. I have used the following query to search a field called tags that has an array of text as it\'s data type:

相关标签:
2条回答
  • 2020-12-11 02:04

    Here is another way to do it within the WHERE clause:

    SELECT COUNT(*)
    FROM planet_osm_ways 
    WHERE (
      0 < (
        SELECT COUNT(*) 
        FROM unnest(planet_osm_ways) AS planet_osm_way
        WHERE planet_osm_way LIKE 'A%'
      )
    );
    
    0 讨论(0)
  • 2020-12-11 02:09

    Use the unnest() function to convert array to set of rows:

    SELECT count(distinct id)
    FROM (
        SELECT id, unnest(tags) tag
        FROM planet_osm_ways) x
    WHERE tag LIKE 'A%'
    

    The count(dictinct id) should count unique entries from planet_osm_ways table, just replace id with your primary key's name.

    That being said, you should really think about storing tags in a separate table, with many-to-one relationship with planet_osm_ways, or create a separate table for tags that will have many-to-many relationship with planet_osm_ways. The way you store tags now makes it impossible to use indexes while searching for tags, which means that each search performs a full table scan.

    0 讨论(0)
提交回复
热议问题