[英]Postgres Query of an Array using LIKE
I am querying a database in Postgres using psql. 我正在使用psql查询Postgres中的数据库。 I have used the following query to search a field called tags that has an array of text as it's data type:
我使用以下查询来搜索名为tags的字段,该字段具有文本数组作为其数据类型:
select count(*) from planet_osm_ways where 'highway' = ANY(tags);
I now need to create a query that searches the tags fields for any word starting with the letter 'A'. 我现在需要创建一个查询,在标签字段中搜索以字母“A”开头的任何单词。 I tried the following:
我尝试了以下方法:
select count(*) from planet_osm_ways where 'A%' LIKE ANY(tags);
This gives me a syntax error. 这给了我一个语法错误。 Any suggestions on how to use LIKE with an array of text?
有关如何使用LIKE与文本数组的任何建议?
Use the unnest()
function to convert array to set of rows: 使用
unnest()
函数将数组转换为行集:
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. count(dictinct id)
应该计算planet_osm_ways
表中的唯一条目,只需用您的主键名称替换id
。
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
. 话虽这么说,你应该考虑将标签存储在一个单独的表中,与
planet_osm_ways
有planet_osm_ways
关系,或者为与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. 现在存储标签的方式使得在搜索标签时无法使用索引,这意味着每次搜索都会执行全表扫描。
Here is another way to do it within the WHERE
clause: 这是在
WHERE
子句中执行此操作的另一种方法:
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%'
)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.