不使用mysql中的分析函数的RANK函数的性能

时间:2017-04-27 18:04:06

标签: mysql sql

我正在尝试计算测试表中每个分区的排名,但我想知道在mysql中实现排名函数的有效方法是什么?

是否使用变量或相关子查询,如果数据量很大,哪一个是有效的?

SQL Code :-



CREATE TABLE Test1(A int,B int, C int);


   INSERT INTO Test1 VALUES(1,11,20);

   INSERT INTO Test1 VALUES(1,11,21);

   INSERT INTO Test1 VALUES(1,11,22);

   INSERT INTO Test1 VALUES(1,12,23);

   INSERT INTO Test1 VALUES(1,12,24);

   INSERT INTO Test1 VALUES(1,12,25);

   INSERT INTO Test1 VALUES(2,13,26);

   INSERT INTO Test1 VALUES(2,13,27);

   INSERT INTO Test1 VALUES(2,13,28);

   INSERT INTO Test1 VALUES(2,14,29);

   INSERT INTO Test1 VALUES(2,14,30);

   INSERT INTO Test1 VALUES(2,14,31);

   INSERT INTO Test1 VALUES(3,15,32);

   INSERT INTO Test1 VALUES(3,15,33);

   INSERT INTO Test1 VALUES(3,14,34);

   INSERT INTO Test1 VALUES(3,14,35);

   INSERT INTO Test1 VALUES(3,14,36);

   INSERT INTO Test1 VALUES(4,15,36);

   INSERT INTO Test1 VALUES(4,15,37);

   INSERT INTO Test1 VALUES(4,15,38);



 Query :-

 SELECT t1.A,t1.B,t1.C,  
        ( SELECT COUNT(*)
            FROM test1 t2        
           WHERE t1.C >= t2.C        
             AND t1.A = t2.A      
             AND t1.B = t2.B     
         ) AS rn 
   FROM test1 t1; 




  Output:-

+------+------+------+------+
| A    | B    | C    | rn   |
+------+------+------+------+
|    1 |   11 |   20 |    1 |
|    1 |   11 |   21 |    2 |
|    1 |   11 |   22 |    3 |
|    1 |   12 |   23 |    1 |
|    1 |   12 |   24 |    2 |
|    1 |   12 |   25 |    3 |
|    2 |   13 |   26 |    1 |
|    2 |   13 |   27 |    2 |
|    2 |   13 |   28 |    3 |
|    2 |   14 |   29 |    1 |
|    2 |   14 |   30 |    2 |
|    2 |   14 |   31 |    3 |
|    3 |   15 |   32 |    1 |
|    3 |   15 |   33 |    2 |
|    3 |   14 |   34 |    1 |
|    3 |   14 |   35 |    2 |
|    3 |   14 |   36 |    3 |
|    4 |   15 |   36 |    1 |
|    4 |   15 |   37 |    2 |
|    4 |   15 |   38 |    3 |
+------+------+------+------+

1 个答案:

答案 0 :(得分:0)

我喜欢加入。事实上,即使我主要使用SQL Server,我有时会放弃使用rank()函数并自己构建它以确保我能够牢牢理解数据。

以下是一个例子:

select t1.*, COUNT(t2.A) as m -- could count over any thing from t2, doesn't have to be A
    from Test1 t1
    left join Test1 t2
        on t2.A = t1.A
        and t2.B = t1.B
        and t2.C <= t1.C
    group by  t1.A
            , t1.B
            , t1.C
    order by  t1.A
            , t1.B
            , t1.C

这将与排名相同,您可以更改您的加入条件,以多种方式排名。

删除该组,然后使用select *查看其工作原理的详细信息。