使用SQL(对于MySQL),如何基于前一行的数据更新行上的数据?

使用SQL(对于MySQL),如何基于前一行的数据更新行上的数据?,mysql,sql,Mysql,Sql,我在scott列中列出了这些产品SKU,它们是字母数字,应该始终包含数字,但不总是字母。id列是自动递增的。所有数据都是从CSV文件逐行导入的,因此我知道数据的顺序是正确的 从这张图片中可以看到,一些scott字段只是字母,前面应该有前面的数字。例如,在ID5149上,我希望scott是3780a 所以问题是:使用SQL,我如何按顺序分析行,将scott数从包含数字的最新字段前置到后面不包含数字的字段?这里有一个选项,使用用户定义的变量来确定上一个最新的数值 update t set scott

我在scott列中列出了这些产品SKU,它们是字母数字,应该始终包含数字,但不总是字母。id列是自动递增的。所有数据都是从CSV文件逐行导入的,因此我知道数据的顺序是正确的

从这张图片中可以看到,一些scott字段只是字母,前面应该有前面的数字。例如,在ID5149上,我希望scott是3780a


所以问题是:使用SQL,我如何按顺序分析行,将scott数从包含数字的最新字段前置到后面不包含数字的字段?

这里有一个选项,使用用户定义的变量来确定上一个最新的数值

update t
set scott = CONCAT(
           (select scott
            from tablename
            where id = t.id - 1),
            scott)
from tablename t
where Scott not like '%0%'
and Scott not like '%1%'
and Scott not like '%2%'
and Scott not like '%3%'
and Scott not like '%4%'
and Scott not like '%5%'
and Scott not like '%6%'
and Scott not like '%7%'
and Scott not like '%8%'
and Scott not like '%9%'
update yourtable y
join (
  select id, scott, @prevNumericId:=
          if(scott REGEXP '^[0-9]+$', scott, @prevNumericId) prevNumericId
  from yourtable, (select @prevNumericId:=0) t
  order by id   
  ) t on y.id = t.id and y.scott = t.scott
set y.scott = concat(t.prevNumericId,y.scott)
where y.scott not REGEXP '^[0-9]+$'

那个好老的第一个或者在这种情况下,最后一个孩子的问题,但这次是在同一张桌子上

这对您来说应该可以非常优雅地完成工作:

UPDATE mytable dest
JOIN (
SELECT mt.id, CONCAT(lnk.scott, mt.scott) AS newValue
FROM mytable mt

LEFT OUTER JOIN mytable lnk ON lnk.id < mt.id AND CONCAT('',SUBSTRING(lnk.scott, 1, 1) * 1) != 0
LEFT OUTER JOIN mytable lnk2 ON lnk2.id < mt.id AND CONCAT('',SUBSTRING(lnk2.scott, 1, 1) * 1) != 0
    AND lnk.id < lnk2.id

WHERE lnk2.id IS NULL
AND CONCAT('',SUBSTRING(mt.scott, 1, 1) * 1) = 0
) AS source on source.id = dest.id

SET dest.scott = source.newValue
===

我没有足够的代表发表评论,但@sgeddes的解决方案基本相同,只是使用了用户定义的变量。只要变量不在并发执行之间交叉,就可以了:

不管怎样,这个版本都将愉快地并发运行