I have two tables: one with points, the other with polys.
CREATE TABLE `points` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`point` point NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
CREATE TABLE `ranges` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`poly` polygon NOT NULL,
PRIMARY KEY (`id`),
SPATIAL KEY `poly` (`poly`)
) ENGINE=MyISAM;
I want to join ranges to points on points inside polys. Queries look simple:
SELECT *
FROM points
LEFT JOIN ranges
ON MBRCONTAINS(poly, point)
WHERE points.id = 2;
This query works fast and uses indexes, part of explain:
table | type | possible_keys | key | key_len ranges | range | poly | poly | 34
But, when I try to join with several rows from table points
:
SELECT *
FROM points
LEFT JOIN ranges
ON MBRCONTAINS(poly, point)
WHERE points.id IN (1,2,3);
everything breaks down:
+----+-------------+------------+-------+---------------+---------+---------+------+--------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+-------+---------------+---------+---------+------+--------+-------------+ | 1 | SIMPLE | points | range | PRIMARY | PRIMARY | 4 | NULL | 3 | Using where | | 1 | SIMPLE | ranges | ALL | poly | NULL | NULL | NULL | 155183 | | +----+-------------+------------+-------+---------------+---------+---------+------+--------+-------------+
Adding FORCE INDEX (poly)
does not help.
Sample data to test queries (sorry, only php version, I'm not common with SQL procedures):
//points
for($i=0;$i<=500;$i++) {
$point = mt_rand();
mysql_query('INSERT INTO points (point) VALUES (POINTFROMWKB(POINT('.$point.', 0)))');
}
$qty = 20000;
$max = mt_getrandmax();
$add = $max / $qty
$end = 0;
//polys
while($end < $max) {
$start = $end;
$end = mt_rand($start, $start + $add);
mysql_query('INSERT INTO ranges (poly) VALUES (
GEOMFROMWKB(POLYGON(LINESTRING(
POINT('.$start.', -1),
POINT('.$end.', -1),
POINT('.$end.', 1),
POINT('.$start.', 1),
POINT('.$start.', -1)
)))
)');
}