我在我当前的项目中使用MySql服务器,需要帮助来提供迁移。我有一个表'Patterns‘,它有一个字段'title’和一个名为'alias‘的新字段,它的值对于所有行都是NULL。我需要使用next算法在此字段中写入:
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实现这样的效果,提前感谢您的帮助
发布于 2017-04-14 21:42:20
这是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 ;https://stackoverflow.com/questions/43412696
复制相似问题