I work with tables that have a lot of data and I'm trying to reduce the request time. There are just a few foreign keys on the tables and a lot of indexes.
If I add foreign keys instead of indexes will querying be faster?
I work with tables that have a lot of data and I'm trying to reduce the request time. There are just a few foreign keys on the tables and a lot of indexes.
If I add foreign keys instead of indexes will querying be faster?
(Your question is ambiguous; I will answer it in a couple of ways.)
SELECT ... FROM a JOIN b ON a.x = b.x
will benefit with INDEX(x)
on either table. You could either explicitly create INDEX(x)
or let FOREIGN KEY ...
create it for you. The end result is the same -- the JOIN
will run a lot faster.
If, by "2 index on the field joining", you really mean "a 'composite' index when 2 columns are used for joining", then
SELECT ...
FROM a
JOIN b
ON a.x = b.x AND a.y = b.y
Together with the composite (multi-column) INDEX(x,y)
will perform well.
Note: This will not be as useful: INDEX(x), INDEX(y)
.
A 3rd example:
SELECT ...
FROM a
JOIN b ON a.x = b.x
WHERE b.z = 123
The optimal indexes are likely to be
b: INDEX(z)
a: INDEX(x)
That is, handling one table in the WHERE
clause before considering the JOIN
is usually best.
More: Index Cookbook