Latest change: ORDER BY timestamp DESC LIMIT 1 - Efficient?
I have开发者_如何学Go a simple save-log:
XiD (INT) what was saved
UiD (INT) who done it
TiD (TIMESTAMP) CURRENT_TIMESTAMP
With all three fields in the primary key - to make it unique.
I want to inform the user of only the latest log-line (until she asks for more):
SELECT UiD,TiD FROM log WHERE XiD=? ORDER BY TiD DESC LIMIT 1
But what happens if there are a billion records with the same XiD ?
Is the above efficient or will the MySql-server examine all the records (for ORDER BY) - And if so: How do I extract the single latest record of a log like that, using the least server-calories ?PS: I havent implemented anything yet, so any alternative scheme is possible : )
EDIT:
Perhaps it would be more efficient simply to store (overwrite) who and when (UiD+TiD) directly in fields on the XiD-record (besides in the log), so I can get them directly, only looking in the log when the user asks for more log-lines explicitly..No, the engine will not examine all the records forSorry, missed this But what happens if there are a billion records with the same XiD ?. Yes, the engine will examine all the records for theORDER BY
. It will examine all those records returned by theWHERE
clause.ORDER BY
clause. Here is the order of operations, as explained by Ben Nadel:- FROM clause
- WHERE clause
- GROUP BY clause
- HAVING clause
- SELECT clause
- ORDER BY clause
IMHO, I don't think there can be any better way to extract the single latest record.
You need index on XiD ASC, TiD DESC to do that. Since UiD is not in the where clause of the query, and TiD is after UiD in the index, it cannot be used for sorting (which is indicated by filesort in the explain query results)
if your 'XID' columns has '*AUTO_INCREMENT*' U can use:
SELECT UiD,TiD FROM log WHERE XiD=LAST_INSERT_ID() ORDER BY TiD DESC LIMIT 1
ref: MySQL Manual
精彩评论