Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

sql - Postgres Query of an Array using LIKE

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:

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'. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...