Select incremented integer

百般思念 提交于 2019-12-18 16:55:07

问题


I want to know if it's possible to select incremented integer from mysql table? and if it does possible, how can I achieve that?

My case is, I have a bunch of data and I need to do INSERT INTO newtable ... SELECT somefield FROM sometable. However, there is one field on newtable called counter that I need it in incremented integer, eg:

row #1: counter=1
row #2: counter=2
row #3: counter=3
row #4: counter=4
row #5: counter=5
row #6: counter=6
... and so on...

I can do this using simple php script, but I want to try to do it all from mysql query. So, can you guys tell me if it's possible?


回答1:


Try this:

INSERT INTO newTable(someField, counter)
SELECT a.someField, (@rank:=@rank+1) AS counter
  FROM sometable a INNER JOIN 
       (SELECT @rank :=0) b


来源:https://stackoverflow.com/questions/5073884/select-incremented-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!