用于设置列值的SQL与下一行的列值相同

时间:2014-09-11 14:53:23

标签: mysql sql

我有一张这样的表

--------------------------
id    some_column
--------------------------
1      null
2      abc
3      null
4      null
5      def
6      ghi

在我的场景中,表中的一些初始行在some_column中为null。 所有最新行都正确设置了some_column值

我想运行一个查询,它可以通过从下一个非空值复制值来替换some_column的所有空值。

例如,运行查询后,表格将变为

--------------------------
id    some_column
--------------------------
1      abc
2      abc
3      def
4      def
5      def
6      ghi

我正在尝试这样的事情

update table as t1 set some_column = (select some_column from table as t2 where t2.id > t1.id and t2.some_column is not null limit 1) where some_column is null

但是收到错误

You can't specify target table 't1' for update in FROM clause

2 个答案:

答案 0 :(得分:1)

您可以使用带有order by和limit的相关子查询来获取空值后的第一个not null值,请参阅select demo以获取相关子查询,下面的查询将使用下一个不更新列的null值空值

update t 
join(
select t1.*,
(select some_column 
 from t where id > t1.id 
 and some_column is not null
order by id limit 1
) newname
from t t1
  ) t2
on t.id = t2.id 
set t.some_column =t2.newname
where t.some_column is null

Demo

答案 1 :(得分:1)

您可以使用JOIN

执行此操作
UPDATE t AS t0
JOIN (
    SELECT t1.id, MIN(t2.id) new_id
    FROM t AS t1
    JOIN t AS t2 ON t1.id < t2.id
    WHERE t1.some_column IS NULL
    AND t2.some_column IS NOT NULL
    GROUP BY t1.id) AS tnew ON t0.id = tnew.id
JOIN t AS t3 ON t3.id = tnew.new_id
SET t0.some_column = t3.some_column

tnew子查询将每个ID与空值匹配,其中下一个最高ID具有非空值。然后我将其与原始表连接两次,以配对要更新的行 具有替换值的行中的值。

DEMO