简体   繁体   English

检索列表中每个 ID 的最新时间戳 - MySQL

[英]Retrieve latest timestamp for each Id in list - MySQL

I'm running a command to retrieve all rows for today with IDs matching 1, 2, 3, etc.我正在运行一个命令来检索今天所有 ID 匹配 1、2、3 等的行。

I want to retrieve the latest entry for these IDs for today though.不过,我想检索这些 ID 的最新条目。

So rather than getting:所以而不是得到:

BinID | BinID | Timestamp |时间戳 |

2 | 2 | 29/04/2021 3:49pm 2021 年 4 月 29 日下午 3:49

2 | 2 | 29/04/2021 4:41pm 29/04/2021 下午 4:41

3 | 3 | 29/04/2021 2:24pm 2021 年 4 月 29 日下午 2:24

I want:我想:

BinID | BinID | Timestamp |时间戳 |

2 | 2 | 29/04/2021 4:41pm 29/04/2021 下午 4:41

3 | 3 | 29/04/2021 2:24pm 2021 年 4 月 29 日下午 2:24

Is this possible?这可能吗?

This is the command I'm running at the moment.这是我目前正在运行的命令。

MySqlCommand mysqlcom = new MySqlCommand("SELECT * FROM realtime_gpses WHERE BinId IN (" + binIdsCSVString + ") AND Timestamp >= CURDATE() AND Timestamp < CURDATE() + INTERVAL 1 DAY", mysqlcon);

where binIdsCSVString in this cases is just 2, 3.其中binIdsCSVString在这种情况下仅为 2、3。

You can try this你可以试试这个

Select binid, max(timestamp) from table where ... Group by binid

As an alternative to in (1, 2...) you can generate:作为in (1, 2...)的替代方案,您可以生成:

where (binid = @binid1 or binid=@binid2.....)

You then add the parameters accordingly.然后相应地添加参数。 All of this can be generated dynamically, yet it is parameterized.所有这些都可以动态生成,但它是参数化的。

See SQL select only rows with max value on a column to get row with max value.请参阅SQL select 仅在列上具有最大值的行以获取具有最大值的行。

and maybe even better: Retrieving the last record in each group - MySQL甚至更好: 检索每组中的最后一条记录 - MySQL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM