I need to select the region closest to an x/y coordinate from a table of rectangular regions defined by x1/y1, x2/y2 points. The point is outside of any of the rectangular regions.
I have managed to select the regions that are closest in the x axis and the y axis using two separate queries.
The table has columns zoneid(int), mappath(varchar), type(varchar), x1(int), y1(int), x2(int), y2(int)
Nearest region in X-axis
SELECT *
FROM mapfiles_zones a
WHERE a.mappath=? AND a.y1 <= $y AND a.y2 >= $y
GROUP BY a.zoneid
ORDER BY abs(a.x1 - $x), abs(a.x2 - $x)
LIMIT 1
Nearest region in Y-axis
SELECT *
FROM mapfiles_zones a
WHERE a.mappath=? AND a.x1 <= $x AND a.x2 >= $x
GROUP BY a.zoneid
ORDER BY abs(a.y1 - $y), abs(a.y2 - $y)
LIMIT 1
I am having trouble comparing returned region arrays to determin which is closest in their respective axis.
I cannot use min() on the arrays in PHP because there are other numeric values that end up being analysed. I tried combining the arrays using UNION but get the error
number of bound variables does not match number of tokens
How can I get the closest region from these two results in PHP, or better yet, would it be possible to combine these two queries to return the single closest region?