mySQL 分组依据?

发布于 2024-10-18 06:44:11 字数 257 浏览 2 评论 0原文

假设我在数据库中有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

长发绾君心 2024-10-25 06:44:11

同一个来自 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 your GROUP 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 use MIN, etc.

笑叹一世浮沉 2024-10-25 06:44:11

也许是这样的:

select id, max(date) 
from thetable
group by id

maybe something like:

select id, max(date) 
from thetable
group by id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文