mysql没有分析函数,要想实现组内排序必须自己实现
sql就不分析了 ,只有几行,很简单,基本思想就是自己创建行号。
测试数据:
DROP TABLE test;
CREATE TABLE test( myNAME VARCHAR(10),name1 VARCHAR(10),COUNT1 BIGINT);
DELETE FROM test;
INSERT INTO test VALUES('1','a',2);
INSERT INTO test VALUES('1','b',1);;
INSERT INTO test VALUES('1','c',4);
INSERT INTO test VALUES('1','d',5);
INSERT INTO test VALUES('1','e',7);
INSERT INTO test VALUES('1','f',8);
INSERT INTO test VALUES('2','g',9);
INSERT INTO test VALUES('2','h',0);
INSERT INTO test VALUES('2','i',21);
INSERT INTO test VALUES('2','j',3);
INSERT INTO test VALUES('2','k',4);
INSERT INTO test VALUES('2','1',56);
INSERT INTO test VALUES('3','m',67);
INSERT INTO test VALUES('3','n',89);
INSERT INTO test VALUES('3','o',12);
INSERT INTO test VALUES('3','p',22);
INSERT INTO test VALUES('3','q',23);
INSERT INTO test VALUES('3','r',42);
INSERT INTO test VALUES('3','s',26);
实现sql:
SELECT myNAME, name1, COUNT1
FROM (
SELECT b.myNAME, b.name1, b.count1, IF(@name = b.myNAME, @rank := @rank + 1, @rank := 1) AS rank,@name:=b.myNAME
FROM ( SELECT myNAME, name1, COUNT1 FROM test ORDER BY myNAME ASC, COUNT1 DESC) b,
( SELECT @rownum := 0, @name := NULL, @rank := 0 ) a
) result
WHERE rank<5;
最终输出: