gpt4 book ai didi

mysql - 使用动态确定的值更新表

转载 作者:行者123 更新时间:2023-11-30 22:00:52 24 4
gpt4 key购买 nike

我在当前项目中使用 MySql 服务器,需要帮助来提供迁移。我有一个表“Patterns”,其中有一个字段“title”和一个名为“alias”的新字段,所有行的值为 NULL。我需要使用下一个算法在该字段中写入:

1) if title field is unique: just write it's value in alias
2) if title is not unique: alias = title +'-'+ n , where n is number of occurrence

例如:

________________

|id|title|alias
|1 |smile|null
|2 |smile|null
|3 |smile|null
________________

应转换为:

 ________________

|id|title|alias
|1 |smile|smile
|2 |smile|smile-1
|3 |smile|smile-2
________________

是否可以使用SQL实现这样的结果,在此先感谢您的帮助

最佳答案

这是 MySQL 的一个痛点。您可以使用变量来完成。

select t.*,
(case when tt.cnt > 1 then concat(t.title, '-', rn) else t.title end) as new_title
from (select t.*,
(@rn := if(@t = title, @rn + 1,
if(@t := title, 1, 1)
)
) as rn
from t cross join
(select @rn := 0, @t := '') params
order by title
) t join
(select title, count(*) as cnt
from t
group by title
) tt
on tt.title = t.title;

在许多情况下,您可以在单例中省略“-1”。这简化了查询:

select t.*,
(case when rn > 1 then concat(t.title, '-', rn) else t.title end) as new_title
from (select t.*,
(@rn := if(@t = title, @rn + 1,
if(@t := title, 1, 1)
)
) as rn
from t cross join
(select @rn := 0, @t := '') params
order by title
) t ;

关于mysql - 使用动态确定的值更新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43412696/

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