如何有效地 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 11:59:29  来源:igfitidea点击:

How to efficiently SQL select newest entries from a MySQL database?

sqlmysql

提问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, closingPriceand date; nameand datetogether form a unique index.

表列是name,closingPricedate; namedate一起形成唯一索引。

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

重复:
SQL 查询以获取最新价格

回答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.

您必须为名称和日期添加索引。