gpt4 book ai didi

mysql - 自动增加空字段,保留非空字段

转载 作者:太空宇宙 更新时间:2023-11-03 11:58:58 25 4
gpt4 key购买 nike

我有一个表 items,它有一个字段 priority。字段优先级中的一半元素具有唯一值,范围从 1x。我希望字段 priority 为 null 的元素具有从 x+1y 的增量值。

我试过了

UPDATE items
SET priority = IFNULL(priority, 0)

但这不是我想要的。我希望非空字段保持原样,这是我通过以下方式实现的:

SET priority = IFNULL(priority, 0)

和 null 字段开始从值递增,这是我通过以下获得的:

SELECT MAX(priority)
FROM items;

所以唯一想到的就是接近

UPDATE items
SET priority =
IFNULL(priority, 0) + (SELECT MAX(priority)
FROM items)
WHERE priority IS NULL

但是我不太确定我会怎么做。有任何提示或技巧吗?

最佳答案

可以得到当前的最大优先级,保存在一个变量中。然后,将该值带入查询中,比如使用 cross join。您可以在 set 语句中递增该值:

update items i cross join
(select @x := max(priority) from items) maxp
set priority = (@x := @x + 1)
where priority is null;

关于mysql - 自动增加空字段,保留非空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30531061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com