第3章 优化分组实现有BUG
数据库表脚本如下:
CREATE TABLE IF NOT EXISTS user_kills ( id INT NOT NULL AUTO_INCREMENT, user_id INT NOT NULL, user_name VARCHAR(45) NOT NULL , timestr DATETIME NOT NULL, kills INT NOT NULL , PRIMARY KEY(id) ) DEFAULT CHARACTER SET = utf8;
数据库数据脚本如下:
INSERT INTO `user_kills` VALUES (1, 3, '孙悟空', '2013-01-11 00:00:00', 20); INSERT INTO `user_kills` VALUES (2, 4, '沙僧', '2013-01-10 00:00:00', 3); INSERT INTO `user_kills` VALUES (3, 2, '猪八戒', '2013-01-10 00:00:00', 10); INSERT INTO `user_kills` VALUES (4, 2, '猪八戒', '2013-02-01 00:00:00', 2); INSERT INTO `user_kills` VALUES (5, 2, '猪八戒', '2013-02-05 00:00:00', 12); INSERT INTO `user_kills` VALUES (6, 2, '猪八戒', '2013-02-06 00:00:00', 1); INSERT INTO `user_kills` VALUES (7, 2, '猪八戒', '2013-02-07 00:00:00', 17); INSERT INTO `user_kills` VALUES (8, 2, '猪八戒', '2013-02-11 00:00:00', 5); INSERT INTO `user_kills` VALUES (9, 2, '猪八戒', '2013-02-12 00:00:00', 10); INSERT INTO `user_kills` VALUES (10, 2, '猪八戒', '2013-01-10 00:00:02', 17); INSERT INTO `user_kills` VALUES (11, 2, '猪八戒', '2013-02-01 00:00:01', 17);
执行查询语句如下:
SELECT d.user_name, c.timestr, kills FROM ( SELECT user_id, timestr, kills, (SELECT count(*) FROM user_kills b WHERE b.user_id = a.user_id AND a.kills <= b.kills ) AS cnt FROM user_kills a GROUP BY user_id, timestr, kills ) c JOIN user1 d ON c.user_id = d.id WHERE cnt <= 2;
结果如下:
结果查询不出猪八戒的数据,因为猪八戒的最大杀怪数有三条即以上,所以不显示数据。