如何有效地 SQL 从 MySQL 数据库中选择最新的条目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to efficiently SQL select newest entries from a MySQL database?
提问by skolima
Possible Duplicate:
SQL Query to get latest price
可能重复:
SQL 查询以获取最新价格
I have a database containing stock price history. I want to select most recent prices for every stock that is listed. I know PostreSQL has a DISTINCT ONstatement that would suit ideally here.
我有一个包含股票价格历史的数据库。我想为列出的每只股票选择最近的价格。我知道 PostreSQL 有一个DISTINCT ON语句,非常适合这里。
Table columns are name
, closingPrice
and date
; name
and date
together form a unique index.
表列是name
,closingPrice
和date
; name
并date
一起形成唯一索引。
The easiest(and very uneffective) way is
在最简单的(和非常uneffective)的方法是
SELECT * FROM stockPrices s
WHERE s.date =
(SELECT MAX(date) FROM stockPrices si WHERE si.name = s.name);
Much better approach I found is
我发现更好的方法是
SELECT *
FROM stockPrices s JOIN (
SELECT name, MAX(date) AS date
FROM stockPrices si
GROUP BY name
) lastEntry ON s.name = lastEntry.name AND s.date = lastEntry.date;
What would be an efficient way to do this? What indexes should I create?
这样做的有效方法是什么?我应该创建什么索引?
duplicate of:
SQL Query to get latest price
回答by Vinko Vrsalovic
I think that your second approach is very efficient. What's its problem?
我认为您的第二种方法非常有效。它的问题是什么?
You have to add indexes to name and date.
您必须为名称和日期添加索引。