且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在具有聚合函数的MySQL查询中获取分组记录的第一条记录和最后一条记录?

更新时间:2021-07-12 21:58:42

您要使用GROUP_CONCATSUBSTRING_INDEX:

SUBSTRING_INDEX( GROUP_CONCAT(CAST(open AS CHAR) ORDER BY datetime), ',', 1 ) AS open
SUBSTRING_INDEX( GROUP_CONCAT(CAST(close AS CHAR) ORDER BY datetime DESC), ',', 1 ) AS close 

这避免了昂贵的子查询,并且我发现对于这个特定问题它通常更有效.

This avoids expensive sub queries and I find it generally more efficient for this particular problem.

查看这两个函数的手册页以了解它们的参数,或访问本文,其中包含有关如何执行

Check out the manual pages for both functions to understand their arguments, or visit this article which includes an example of how to do timeframe conversion in MySQL for more explanations.