我有以下数据:
ID | Image
1 | 10
2 | 11
3 |
4 |
5 |
我想用加1之前的行值更新缺失值。
最终输出应为:
ID | Image
1 | 10
2 | 11
3 | 12
4 | 13
5 | 14
我在更新期间考虑过选择,但它不起作用。
UPDATE items AS item1
SET item1.image = (SELECT image
FROM items AS item2
WHERE item2.id < item1.id
ORDER BY item2.id DESC LIMIT 1) + 1
答案 0 :(得分:3)
使用用户变量尝试此解决方案,完整演示如下。
SQL:
-- data
create table items(ID int, Image int);
insert into items values
(1, 10),(2, NULL),(3, NULL),(4, NULL),(5, NULL);
SELECT * FROM items;
-- SQL needed
SET @i = 0;
UPDATE items
SET Image = (IF(Image IS NULL OR Image = '',
@i:=@i+1,
@i:=Image
));
SELECT * FROM items;
输出:
mysql> SELECT * FROM items;
+------+-------+
| ID | Image |
+------+-------+
| 1 | 10 |
| 2 | NULL |
| 3 | NULL |
| 4 | NULL |
| 5 | NULL |
+------+-------+
5 rows in set (0.00 sec)
mysql>
mysql> SET @i = 0;
Query OK, 0 rows affected (0.00 sec)
mysql> UPDATE items
-> SET Image = (IF(Image IS NULL OR Image = '',
-> @i:=@i+1,
-> @i:=Image
-> ));
Query OK, 4 rows affected (0.00 sec)
Rows matched: 5 Changed: 4 Warnings: 0
mysql> SELECT * FROM items;
+------+-------+
| ID | Image |
+------+-------+
| 1 | 10 |
| 2 | 11 |
| 3 | 12 |
| 4 | 13 |
| 5 | 14 |
+------+-------+
5 rows in set (0.00 sec)
答案 1 :(得分:2)
您可以将UPDATE
与JOIN
一起使用到派生表中:
UPDATE Items AS i1
JOIN (
SELECT ID, @n := @n + 1 AS Image
FROM Items
CROSS JOIN (SELECT @n := (SELECT MAX(Image) FROM Items)) AS v
WHERE Image IS NULL
ORDER BY ID
) AS i2 ON i1.ID = i2.ID
SET i1.Image = i2.Image;
派生表使用变量来计算Image
s记录的NULL
值。
答案 2 :(得分:1)
我有同样的问题,并且我对变量(@)使用简单的更新
update items,(select @n := 10) v set `Image`=@n:=@n+1 order by ID asc;
我希望这个查询有用:D
答案 3 :(得分:0)
鉴于您提供的表格不是样本,我会像这样做一些简单易懂的事情:
Update items Set items.Image=items.id+9 WHERE items.Image is NULL;
天啊,我闻到了传入的投票!