[英]SQL for setting column value same as next row's column value
I have a table like this 我有这样的桌子
--------------------------
id some_column
--------------------------
1 null
2 abc
3 null
4 null
5 def
6 ghi
In my scenario, some initial rows in the table have null in some_column. 在我的场景中,表中的某些初始行在some_column中为null。 All the latest rows have some_column value properly set .
所有最新的行均已正确设置some_column值 。
I want to run a query which can replace all the null values of some_column by copying value from next not null value. 我想运行一个查询,该查询可以通过从下一个非null值复制值来替换some_column的所有null值。
For example, after running the query, table will become 例如,运行查询后,表将变为
--------------------------
id some_column
--------------------------
1 abc
2 abc
3 def
4 def
5 def
6 ghi
I was trying something like this 我正在尝试这样的事情
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
but getting error 但出现错误
You can't specify target table 't1' for update in FROM clause
You can use a correlated subquery with order by and limit to get the first not null value after a null value see select demo for a correlated subquery,below query will update the null values of column with the next not null value 您可以使用带排序和限制的相关子查询来获取空值后的第一个非空值,请参阅选择相关子查询的演示 ,以下查询将使用下一个非空值更新列的空值
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
You can do it with a JOIN
: 您可以使用
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
The tnew
subquery matches up each ID with a null value with the next highest ID with a non-null value. tnew
子查询将具有空值的每个ID与具有非空值的下一个最高ID匹配。 I then join this twice with the original table, to pair up the row to be updated with the value from the row with the replacement value. 然后,我将其与原始表连接两次,以将要更新的行与该行的值与替换值配对。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.