How to select where st_contains one or more points

195 Views Asked by At

How can I select all rows where a polygon column st_conatins one or more points, I have a list of points and I want to select all rows where at least one of the points is in thiere polygon

For example, this query will give me all areas that contain a single point

SELECT *
FROM areas
WHERE ST_Contains(areas.geometry, POINT('lon', 'lat'))

But what I want is to test against multiple points (like IN query), hypothetical code would be

SELECT *
FROM areas
WHERE ST_Contains(areas.geometry, IN(POINT('lon', 'lat'), POINT('lon2', 'lat2'), POINT('lon3', 'lat3')))

Thank you.

2

There are 2 best solutions below

0
Georg Richter On BEST ANSWER

Instead of checking each single point use a collection of points with `MULTIPOINT'

SET @mp:= GeomFromText('MULTIPOINT(1 1, 3 3, 9 9)');
SET @area:= GeomFromText('POLYGON((0 0, 3 0, 3 3, 0 3, 0 0))');

Since ST_CONTAINS returns TRUE only if all points are in the area, you have to use ST_INTERSECTS instead.

select st_intersects(@mp,@area);
+--------------------------+
| st_intersects(@mp,@area) |
+--------------------------+
|                        1 |
+--------------------------+
0
John Mitchell On

Use OR with the WHERE clause.

This will allow multiple different conditions to satisfy the query.

SELECT *
FROM areas
WHERE ST_Contains(areas.geometry, POINT('lon', 'lat'))
OR ST_Contains(areas.geometry, POINT('lon2', 'lat2'))
OR ST_Contains(areas.geometry, POINT('lon3', 'lat3'))