I got a table with over 12 columns. This is the mysql query used to retrive the latest 7 records
SELECT * FROM data WHERE user_id IN(12,10,7,1) HAVING continent IN('Europe','America','Australia') AND NOT MATCH(weather) AGAINST('+"[blues]"' IN BOOLEAN MODE) || continent = 'Asia' AND MATCH(weather) AGAINST('+"[purples]"' IN BOOLEAN MODE) ORDER BY tb_id DESC LIMIT 7
Total rows are more than 5 million and user_id is an indexed column with tb_id being the PRIMARY KEY. When i use the EXPLAIN in front of SELECT. MySQL tells that it will read over 400 thousand records from a total of 5 million.
So should I index continent column or it won’t help in this case?
Here is the EXPLAIN result
id = 1; select_type = SIMPLE; table = data; possible_keys = user_id; key = user_id; ref = NULL; rows = 582; Extra = Using where, Using filesort
First of all, your query is probably wrong. When you use
ORmixed withANDin where or having clause or anywhere, you should use parantheses.Second, using HAVING in your case doesn’t make sense and the optimizer will most likely convert it to a WHERE clause.
The difference between the two is, that
WHEREis applied when determining which rows to select.HAVINGis applied on the result set. So, if the optimizer wouldn’t do a good job, you would first get (almost) all rows, then filter those. When you put it all in theWHEREclause, you get only the relevant rows.HAVING(almost) only makes sense when you are usingGROUP BY.So, you better write your query this way:
To answer your question about the index, post the result of the explain and the create statements of your table
data.