MySQL : Limit + Order By is Slow
Play with the thought you are having a table strucutre like this:
[ Persons ]
ID
Name
[ Occupations ]
ID
Identification
[ Occupation_Relation ]
UserID
OccupationID
Having Indices on all nessesary columns and using a query like this:
select Persons.Name, Occupation.Identification
from Occupation_Relation
inner join Persons
on Occupation_Relation.UserID = Persons.ID
inner join Occupations
on Occupation_Relation.OccupationID = Occupations.ID
where Idenfitication in ('IT')
order by Name
limit 0, 20
This will be VERY slow because having 200 000 Occupation Relations regarding IT, it will use the Order By clause before the limit, thus ordering 200 000 rows.
The simple solution to this problem is having a subselect like this
select Persons.Name, Occupation.Identification
from ( select Persons.Name, Occupation.Identification from Occupation_Relation inner join Persons on Occupation_Relation.UserID = Persons.ID inner join Occupations on Occupation_Relation.OccupationID = Occupations.ID where Idenfitication in ('IT')
limit 0, 20
)
order by Name
This will though give us a major problem having thrown away hunders of thousands of rows. But this will give us 2000 relevant rows to our search and thus solving the performance problem.
The solution forces the User to specifiy the specific searched data.
[ Persons ]
ID
Name
[ Occupations ]
ID
Identification
[ Occupation_Relation ]
UserID
OccupationID
Having Indices on all nessesary columns and using a query like this:
select Persons.Name, Occupation.Identification
from Occupation_Relation
inner join Persons
on Occupation_Relation.UserID = Persons.ID
inner join Occupations
on Occupation_Relation.OccupationID = Occupations.ID
where Idenfitication in ('IT')
order by Name
limit 0, 20
This will be VERY slow because having 200 000 Occupation Relations regarding IT, it will use the Order By clause before the limit, thus ordering 200 000 rows.
The simple solution to this problem is having a subselect like this
select Persons.Name, Occupation.Identification
from ( select Persons.Name, Occupation.Identification from Occupation_Relation inner join Persons on Occupation_Relation.UserID = Persons.ID inner join Occupations on Occupation_Relation.OccupationID = Occupations.ID where Idenfitication in ('IT')
limit 0, 20
)
order by Name
This will though give us a major problem having thrown away hunders of thousands of rows. But this will give us 2000 relevant rows to our search and thus solving the performance problem.
The solution forces the User to specifiy the specific searched data.
Kommentarer
Trackback