这是我的名为logs
的表格:
id package log
====================
0 first log0
1 first log1
2 second log2
我希望查询结果如下:
package count last_log_id
===============================
first 2 1
second 1 2
到目前为止,我的搜索引导我:
SELECT package, COUNT(*) FROM logs 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
这有助于我获取最后一个日志的ID,但计数错了!
package count last_log_id
===============================
first 1 1
second 1 2
答案 0 :(得分:1)
我认为您的第一次尝试是正确的,您可以使用MAX
函数查找每个包的最新日志id
:
SELECT
package,
COUNT(*) AS count,
MAX(id) AS last_log_id
FROM logs
GROUP BY package;