简体   繁体   English

MySQL:选择具有最后一条记录的ID的组的计数

[英]MySQL: Select count of a group with the id of last record

Here is my table called logs : 这是我的表,称为logs

id    package    log
====================
0     first      log0
1     first      log1
2     second     log2

And I want the query result to be like this: 我希望查询结果是这样的:

package    count    last_log_id
===============================
first      2        1
second     1        2

So far, my searches led me to this: 到目前为止,我的搜索使我意识到了这一点:

SELECT package, COUNT(*) FROM logs GROUP BY package

This helped me getting the count of each group by package. 这有助于我按包获取每个组的数量。

SELECT a1.package, COUNT(*),a1.id 
FROM logs a1 LEFT JOIN logs a2 
ON (a1.package = a2.package AND a1.id < a2.id) 
WHERE a2.id IS NULL 
GROUP BY a1.package

And this helped me getting the id of the last log, but the count is wrong! 这有助于我获取上一个日志的ID,但计数错误!

package    count    last_log_id
===============================
first      1        1
second     1        2

I think your first attempt is correct, and you may use the MAX function to find the latest log id for each package: 我认为您的第一次尝试是正确的,您可以使用MAX函数查找每个软件包的最新日志id

SELECT
    package,
    COUNT(*) AS count,
    MAX(id) AS last_log_id
FROM logs
GROUP BY package;

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

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