使用动态确定的值

时间:2017-04-14 13:37:09

标签: mysql sql

我在当前项目中使用MySql服务器,需要帮助才能提供迁移。我有一个带有字段'title'的表'Patterns'和一个名为'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实现此类结果,请提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

这是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 ;