slow mysql query that has to execute hundreds of thousand of times per hour

天大地大妈咪最大 提交于 2019-12-11 02:51:26

问题


My mysql database has a table with several hundred thousand rows. Each row has (amongst other data) a user name and a time stamp.

I need to retrieve the record with the most recent timestamp for a given user.

The current, brute force query is:

SELECT * FROM tableName WHERE `user_name`="The user name" AND datetime_sent = (SELECT MAX(`datetime_sent`) FROM tableName WHERE `user_name`="The user name");

The table has an index on user_name and on datetime_sent.

How can I best improve this query? I have to run thousands of these queries at a time. Each query seems to be taking between 1 and 4 milliseconds and I suspect there is a much more efficient way to achieve the same result.


回答1:


select * from tableName
where userName = 'username'
order by datetime_sent desc
limit 1


来源:https://stackoverflow.com/questions/8754675/slow-mysql-query-that-has-to-execute-hundreds-of-thousand-of-times-per-hour

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