MySQL - SELECT + JOIN + ORDER BY performance

折月煮酒 提交于 2019-12-09 19:41:03

问题


I'm having two tables, I need to select some data joined from both of them

SELECT f.* 
FROM file_data f
JOIN subscriptions s ON f.uid = s.elementid
WHERE s.uid = 119762 AND f.private=0  
ORDER BY f.date DESC

Now, even for a small set of data the query takes over a second. This is due to 'filesort' and 'temporary' used on "subscriptions", caused by ORDER BY f.date (removing that condition causes the time to drop under 0.01s)

Can anyone tell me how to speed up the query?

Here's the result of EXPLAIN

id  select_type    table    type   possible_keys    key            key_len  ref           rows  Extra
1    SIMPLE         s        ref    uid_elementid    uid_elementid  4        const         171   Using index; Using temporary; Using filesort
1    SIMPLE         f        ref    uid_uname        uid_uname      5        s.elementid   22    Using where

回答1:


You should put an index on f.date




回答2:


When an index will help an order by is non-trivial to predict. It is very rarely as simple as "index the fields in the order by". This link has the nitty-gritty details. If you think you have proper indexing and the optimizer just isn't deciding to use them, use an index hint to suggest the index to the database server.




回答3:


I met the same problem,this is my solution:

SELECT f.* 
FROM (SELECT * FROM file_data WHERE `private`=0 ORDER BY `date` DESC ) f
JOIN subscriptions s ON f.uid = s.elementid
WHERE s.uid = 119762


来源:https://stackoverflow.com/questions/4305324/mysql-select-join-order-by-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!