Reputation: 2122
I have a table fs_city
, with 3 millions cities all around the world, as well as a table fs_country
.
When the user visits the website it detects its country code, the user is required to select their country and city from a box (which looks for cities in fs_city
on key press), if the user is from USA, and types "Ne", he will get a drop down list with "New York" for i.e. I do this to create an autocomplete input.
The problem is that, the query is sent upon every key press, in my example "Ne", there are two queries to the table fs_city
.
Also, even if there's only one query, it takes 6 seconds to return a response from that table... My table has primary keys.
This is my SQL query:
SELECT
ci.city_id,
ci.country_code,
ci.city,
ci.region,
co.country_name
FROM
fs_city as ci,
fs_country as co
WHERE
ci.city LIKE "Ne%"
AND co.country = ci.country_code
AND ci.country_code = :country
ORDER BY
ci.city ASC
LIMIT 0,20
How can I create an autocomplete feature (with keypress), and how to speed up fs_city
table queries?
Updated :
fs_city primary key : city_id
fs_country primary key : country_id
Engine : InnoDB
Upvotes: 0
Views: 1491
Reputation: 378
jQuery has nice widget with exactly what you are looking for and I'm pretty sure you can limit it to only start query the database after a set amount of characters so you can limit your results. That should solve your speed problem and shorten your javascript. http://jqueryui.com/autocomplete/
EDIT MySQL also has a LIMIT term to cap the return, which might also help.
Upvotes: 1