Here is my table called 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!
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:
SELECT
package,
COUNT(*) AS count,
MAX(id) AS last_log_id
FROM logs
GROUP BY package;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.