Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

mysql - sql loop and set properties

In SQL, I would like to query a list, in order by pageNumber

SELECT * FROM `comics` 
WHERE 1
ORDER BY pageNumber ASC

Then, I would like to set their pageNumbers based on their index in the query (starting with 1 instead of 0).

Here is my pseudo code for the functionality as desired; where list is the return value of the Select Query above.

for(var n:int = 0; n<list.length; n++){
    if(list[n].pageNumber != n+1){
        list[n].pageNumber = n+1
    }
}

For example I might have pageNumbers 5, 17, 23, 24, 18, 7

The ORDER BY pageNumber ASC will sort this to 5, 7, 17, 18, 23, 24

I would then like to alter the pageNumbers in order to be 1, 2, 3, 4, 5, 6

edit:

@fortheworld MySQL

@cyberkiwi UPDATE

sorry for being unclear. guess i need to learn more for my questions to be clear :) thanks for all your help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
SET @I := 0;

  SELECT *,
         @I := @I + 1 AS newPageNumber
    FROM comics
ORDER BY pageNumber ASC

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...