1

Can spatial indexes be used for joining tables in mysql?

I have two tables with a GEOMETRY column and a spatial index on it. The table is MyISAM. I would like to join these tables on the rows which intersect. I cannot get mysql to use the spatial indexes despite using FORCE INDEX in my query.

The query is:

SELECT * 
FROM a FORCE INDEX FOR JOIN (asidx) 
JOIN b FORCE INDEX FOR JOIN (bsidx) 
     ON Intersects(a.g, b.g) -- g is the name of the GEOMETRY

The explain plan is:

| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows  | Extra                          |
|  1 | SIMPLE      | a     | ALL  | asidx         | NULL | NULL    | NULL | 50000 |                                |
|  1 | SIMPLE      | b     | ALL  | bsidx         | NULL | NULL    | NULL | 50000 | Using where; Using join buffer |

Why aren't the indexes use? For 50k rows tables it runs for 15 minutes. How can I make it faster?

1 Answer 1

1

Yes, spatial indexes can be used for joins, but you aren't using an index for your join.

In order for a index to be used for a search, MySQL needs a constant, or an expression that refers to a data column that has already been read.

You're not referencing an indexed column in your ON clause. You're referencing 0 or 1, which is the result of the INTERSECTS() function.

Your ON clause specifies a function on columns from both tables in the join. MySQL won't have the column values required for the function until both records are already read, so no index can be used for the join, requiring a full scan.

Basically, MySQL doesn't know if two records go together until it tries it, so it must try every combination.

Perhaps a better solution would be to precalculate a table of intersection pairs, store them in a separate (junction) table, and join that way.

Sign up to request clarification or add additional context in comments.

1 Comment

Since I need the intersecting records, there would be nothing to pre-calculate. There is just the calculation of the intersection. Are you saying that there is no way to speed it up?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.