【问题标题】:mysql move the last N characters of each line of data to the next linemysql将每行数据的最后N个字符移动到下一行
【发布时间】:2020-08-04 08:08:27
【问题描述】:

我想将每行数据的最后3个字符移到下一行,第一行用xxx填充。

示例:

现在我有 TableOne,我想要 TableTwo,谢谢!

[更新]

mysql版本为5.7.22,不支持lag功能

【问题讨论】:

  • 你为什么要这么做?
  • 你的 MySql/MariaDB 版本是多少?

标签: mysql database mariadb


【解决方案1】:

如果您的 MySql/MariaDB 版本支持窗口函数并且您已经创建了 TableTwo,您可以像这样插入新行:

insert into TableTwo(id, num)
select
  id,
  concat(
    coalesce(lag(right(num, 3)) over (order by id), 'xxx'), 
    coalesce(left(num, 2), '')
  ) num
from (
  select * from TableOne
  union all
  select max(id) + 1, null from TableOne
) t;

请参阅demo。

如果没有窗口函数,您可以使用自连接来完成:

insert into TableTwo(id, num)
select
  t.id,
  concat(
    coalesce(right(t1.num, 3), 'xxx'), 
    coalesce(left(t.num, 2), '')
  ) num
from (
  select * from TableOne
  union all
  select max(id) + 1, null from TableOne
) t left join TableOne t1
on t1.id = t.id - 1;

请参阅demo。

结果:

> id | num  
> -: | :----
>  1 | xxxab
>  2 | cde01
>  3 | 23456
>  4 | 789

【讨论】:

  • 谢谢!但是我的mysql版本是5.7.22,不支持lag功能
  • @artwl 查看我的第二个查询。如果 id 之间没有间隙,它将起作用。
猜你喜欢
  • 1970-01-01
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-26
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
相关资源
最近更新 更多