I've got this SQL:
SELECT COUNT( d.id ) AS sum, d.user_agent
FROM debug AS d
WHERE d.id IN (
SELECT MAX(d2.id)
FROM debug AS d2
GROUP BY d2.user_id
)
GROUP BY d.user_agent
I want to get the amounts of similar useragents but only the useragents of the last entry of each user.
=> COUNT(d.id)
=> GROUP BY d2.user_id
I tried both SQLs separated and wrote the response of the subquery plain in the other query. The execution time was far under a second. Both together about 25 seconds.
My table structure:
CREATE TABLE `debug` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`event` varchar(127) NOT NULL,
`user_id` int(11) NOT NULL,
`user_agent` varchar(255) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`parameters` varchar(5000) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `user_agent` (`user_agent`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL-Fiddle: Here
Any ideas how I can optimize it?
Is this any better?
SELECT x.user_agent
, COUNT(*) total
FROM debug x
JOIN
( SELECT user_id
, MAX(id) max_id
FROM debug
GROUP
BY user_id
) y
ON y.user_id = x.user_id
AND y.max_id = x.id
GROUP BY user_agent;
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.