mysql求分組的前3名
具體思路就是,查詢出當前資料表裡,每一條資料在當前分組裡的排名。-- 效率不咋滴 誰有更好的方法--
SELECT
a.*FROM
(
SELECT
t1.*,
(
SELECT
count(*) + 1
FROM
tst
WHERE
test = t1.test
AND num > t1.num
) AS bbb
FROM
tst t1
) AS a
WHERE
bbb <= 3
ORDER BY
test,
num DESC
實現的sql
===測試表結構==========
/*
Navicat Premium Data Transfer
Source Server : 10.1.3.211本地
Source Server Type : MySQL
Source Server Version : 50160
Source Host : 10.1.3.211
Source Database : test
Target Server Type : MySQL
Target Server Version : 50160
File Encoding : utf-8
Date: 08/24/2016 16:32:09 PM
*/
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for `tst`
-- ----------------------------
DROP TABLE IF EXISTS `tst`;
CREATE TABLE `tst` (
`test` varchar(255) DEFAULT NULL,
`num` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of `tst`
-- ----------------------------
BEGIN;
INSERT INTO `tst` VALUES ('a', '1'), ('a', '2'), ('a', '3'), ('a', '4'), ('b', '1'), ('b', '2'), ('b', '3'), ('b', '4');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;