数据库
首页 > 数据库> > MySQL 5.6 – DENSE_RANK之类没有Order By的功能

MySQL 5.6 – DENSE_RANK之类没有Order By的功能

作者:互联网

我有这样一张桌子:

+------+-----------+
|caseID|groupVarian|
+------+-----------+
|1     |A,B,C,D,E  |
+------+-----------+
|2     |A,B,N,O,P  |
+------+-----------+
|3     |A,B,N,O,P  |
+------+-----------+
|4     |A,B,C,D,F  |
+------+-----------+
|5     |A,B,C,D,E  |
+------+-----------+

我想获得一个新的列名称Varian,这样相同的groupVarian值具有由nameVarian表示的相同排名(例如:v1,v2等).但是,分配给特定groupVarian的nameVarian值应该按caseID的顺序排列(按照它们出现在表中的顺序).

输出应该是这样的:

+------+-----------+----------+
|caseID|groupVarian|namevarian
+------+-----------+----------+
|1     |A,B,C,D,E  |v1        |
+------+-----------+----------+
|2     |A,B,N,O,P  |v2        |
+------+-----------+----------+
|3     |A,B,N,O,P  |v2        |
+------+-----------+----------+
|4     |A,B,C,D,F  |v3        |
+------+-----------+----------+
|5     |A,B,C,D,E  |v1        |
+------+-----------+----------+

解决方法:

对于MySQL版本< 8.0(OP’s version is 5.6):

问题陈述看起来需要DENSE_RANK功能而不是groupVarian;但事实并非如此. As explained by @Gordon Linoff

You appear to want them enumerated by the order they appear in the
data.

假设您的表名是t(请相应地更改您的代码的表和字段名称).这是一个approach utilizing session variables(对于旧版本的MySQL),给出了所需的结果(DB Fiddle):

SET @row_number = 0;
SELECT t3.caseID, 
       t3.groupVarian, 
       CONCAT('v', t2.num) AS nameVarian
FROM
  (
   SELECT 
     (@row_number:=@row_number + 1) AS num, 
     t1.groupVarian 
   FROM 
     (
      SELECT DISTINCT groupVarian 
      FROM t 
      ORDER BY caseID ASC 
     ) AS t1 
  ) AS t2 
INNER JOIN t AS t3 
  ON t3.groupVarian = t2.groupVarian 
ORDER BY t3.caseID ASC 

另外:我之前尝试模拟DENSE_RANK功能,效果很好.虽然之前的查询也可以稍微调整一下,以实现DENSE_RANK功能.但是,以下查询更有效,因为它创建较小的派生表,并避免在groupVarian上加入:

SET @row_number = 1;
SET @group_varian = '';

SELECT inner_nest.caseID, 
       inner_nest.groupVarian, 
       CONCAT('v', inner_nest.num) as nameVarian 
FROM (
        SELECT 
            caseID, 
            @row_number:=CASE
                           WHEN @group_varian = groupVarian THEN @row_number
                           ELSE @row_number + 1
                         END AS num, 
            @group_varian:=groupVarian as groupVarian 
        FROM
            t  
        ORDER BY groupVarian
     ) AS inner_nest 
ORDER BY inner_nest.caseID ASC 

标签:mysql-5-6,sql,mysql
来源: https://codeday.me/bug/20190827/1746269.html