如何在MySQL5.7中实现行号功能?

pn9klfpd  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(533)

表名:表1列:(id,ref\u id,timestamp)

|**id**|**ref_id**|  **timestamp**     |                              
| 1      | 111        | 2020-04-27 02:59:45    |           
| 2      | 111        | 2020-04-28 02:59:45    |            
| 3      | 111        | 2020-04-26 02:59:45    |

我想实现一些

DELETE 
FROM   (
           SELECT *,
                  ROW_NUMBER() OVER(PARTITION BY red_id ORDER BY TIMESTAMP DESC) AS rn
           FROM   table_one
       ). 
       s
WHERE  r.rn != 1;

执行上述删除查询后的表1应该如下所示

|**id**|**ref_id**|  **timestamp**                                             
| 2      | 111        | 2020-04-28 02:59:45    |

我试图选择需要删除的行,但没有得到正确的行号。请在下面找到我的问题:

SET @row_number : = 0;   
SELECT *
FROM   (
           SELECT @row_number: = CASE 
                                      WHEN @ci = ref_id THEN @row_number + 1
                                      ELSE 1
                                 END  AS rn,
                  @ci: = ref_id          ref_id,
                  id,
                  TIMESTAMP
           FROM   table_one
           ORDER BY
                  TIMESTAMP              DESC

提前谢谢。

q3qa4bjr

q3qa4bjr1#

DELETE t1.*
FROM table_one t1, table_one t2
WHERE t1.ref_id = t2.ref_id 
  AND t1.`timestamp` < t2.`timestamp`

或者在连接语法中相同

DELETE t1.*
FROM table_one t1
JOIN table_one t2 ON t1.ref_id = t2.ref_id 
WHERE t1.`timestamp` < t2.`timestamp`

小提琴

jogvjijk

jogvjijk2#

使用 join :

delete t
    from table_one t join
         (select tt.ref_id, max(tt.timestamp) as max_ts
          from table_one tt
          group by tt.ref_id
         ) tt
         on tt.ref_id = t.ref_id
    where t.timestamp < tt.max_ts;

不需要窗口函数。

相关问题