Mysql查询组最新插入

发布于 2025-01-05 11:06:26 字数 449 浏览 0 评论 0原文

我有一个表 tbldevicevaluelog ,其布局如下:

id | ts | dc | data1 | data2

其中 ts 是时间戳,dc 是设备代码。 data1data2 是最新值。

总共有 130 种不同的设备代码。

目标是从每个可用的设备代码中获取最新时间和 data1

通过下面的查询,我可以获得包含所有设备代码和最新时间​​的结果。

SELECT dc, MAX(ts) FROM tbldevicevaluelog GROUP BY dc

问题是如何也获取属于这个最新时间的data1

I have a table tbldevicevaluelog with the following layout:

id | ts | dc | data1 | data2

Where ts is a timestamp, dc is a devicecode. data1 and data2 are the latest value.

In total there are 130 different device codes.

The goal is to get the latest time and data1 from each available device code.

With the query below I can get a result with al the device codes and the latest time.

SELECT dc, MAX(ts) FROM tbldevicevaluelog GROUP BY dc

The question is how to also get the data1 which belongs to this latest time?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

长亭外,古道边 2025-01-12 11:06:26

使用相同的设备代码和时间戳将结果连接回表中。

SELECT tg.dc, tg.latest, t.data1 
FROM tbldevicevaluelog t
JOIN
( SELECT dc, MAX(ts) as latest FROM tbldevicevaluelog GROUP BY dc ) tg
ON tg.dc=t.dc AND tg.latest=t.ts

Join your result back to your table on the same device code and timestamp.

SELECT tg.dc, tg.latest, t.data1 
FROM tbldevicevaluelog t
JOIN
( SELECT dc, MAX(ts) as latest FROM tbldevicevaluelog GROUP BY dc ) tg
ON tg.dc=t.dc AND tg.latest=t.ts
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文