首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用动态确定的值更新表

使用动态确定的值更新表
EN

Stack Overflow用户
提问于 2017-04-14 21:37:09
回答 1查看 29关注 0票数 1

我在我当前的项目中使用MySql服务器,需要帮助来提供迁移。我有一个表'Patterns‘,它有一个字段'title’和一个名为'alias‘的新字段,它的值对于所有行都是NULL。我需要使用next算法在此字段中写入:

代码语言:javascript
复制
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

例如:

代码语言:javascript
复制
________________

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

应转换为:

代码语言:javascript
复制
 ________________

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

有没有可能用SQL实现这样的效果,提前感谢您的帮助

EN

回答 1

Stack Overflow用户

发布于 2017-04-14 21:42:20

这是MySQL中的一个难题。您可以使用变量来完成此操作。

代码语言:javascript
复制
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“。这简化了查询:

代码语言:javascript
复制
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 ;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43412696

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档