我有这个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
我想获得类似的使用者数量,但只获得每个用户最后一个条目的使用者。
=> COUNT(d.id)
=> GROUP BY d2.user_id
我尝试将两个SQL分开并在另一个查询中编写子查询plain的响应。执行时间远远不到一秒钟。 两者在一起约25秒。
我的表结构:
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-小提琴: Here
我可以如何优化它?
答案 0 :(得分:1)
这样更好吗?
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;