mySQL 分组依据?
假设我在数据库中有 5 行,其中三行的 ID 为 2,其中两行的 ID 为 1。ID
为 2 的三行有日期,例如 6 月 1 日、6 月 2 日、6 月 3 日。
ID 为 1 的两个有日期,例如 7 月 1 日和 7 月 2 日。
如何为每个 ID 仅选择 1 个最新值?
当前使用 GROUP BY id 时,它返回每个行的第一行,而不是最新添加的行。
我想要添加最新的...有什么想法吗?
谢谢。
Say I have 5 rows in the database, three of them have an ID of 2, two of them have an ID of 1.
The three with ID of 2 have dates, lets say for example 1st June, 2nd June, 3rd June.
The two with ID of 1 have dates, lets say for example, 1st July, 2nd July.
How do I go about selecting only 1 of the latest values, for each ID?
When currently using GROUP BY id
it is returning the first row for each, not the latest added.
I want the latest one added... any idea?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
同一个来自 SitePoint 的 Kyle R?
SELECT
列表中的每一列都必须出现在GROUP BY
子句中或者是聚合函数,否则返回值未按规范定义,并且 MySQL 可以自由地为您提供任何内容它想要。想想分组意味着什么。获取一些行集,并将它们折叠成代表该组的单行。这样做时,您必须告诉 MySQL 代表行中的每一列应该来自哪一行。如果您希望从组中获得最大价值,请使用
MAX
。如果你想要最小的,你可以使用MIN
等。Same Kyle R from SitePoint?
Every column in your
SELECT
list must either appear in yourGROUP BY
clause or be an aggregate function, otherwise the return value is undefined by specification and MySQL is free to give you anything it wants.Think about what grouping means. Take some set of rows, and collapse them down into a single row representing the group. In doing so, you must tell MySQL from which row each column in the representative row should come. If you want the greatest value from the group, you use
MAX
. If you want the smallest, you useMIN
, etc.也许是这样的:
maybe something like: