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
199 views
in Technique[技术] by (71.8m points)

php - re-order a table based on sort column and another column value

I have a table which has a sort_no column and the sort values are belonging to q_id which corresponds to question id. But, it does not include proper sorting values. Sometimes, the sort numbers are being repeated for different records with the same q_id. I have to refactor this table with unique sort numbers for each question.

This is a sample data I already have:

 id |   name  | sort_no | q_id
-------------------------------
 1  |  val_1  |    1    | 21
 2  |  val_2  |    2    | 21
 3  |  val_3  |    1    | 32
 4  |  val_4  |    3    | 21
 5  |  val_5  |    2    | 32
 6  |  val_6  |    2    | 32
 7  |  val_7  |    1    | 25
 8  |  val_8  |    1    | 21
 9  |  val_9  |    1    | 21
-------------------------------

This is what it should be:

 id |   name  | sort_no | q_id
------------------------------
 1  |  val_1  |    1    | 21
 2  |  val_2  |    2    | 21
 3  |  val_3  |    1    | 32
 4  |  val_4  |    3    | 21
 5  |  val_5  |    2    | 32
 6  |  val_6  |    3    | 32
 7  |  val_7  |    1    | 25
 8  |  val_8  |    4    | 21
 9  |  val_9  |    5    | 21
-------------------------------

Actually, I can fetch the records and put them in a loop and update it by a loop. But, as you know, it takes time and resource. The table is huge with millions of records.

I was wondering if I could do it directly in MySQL with a nested query.

I have no idea about the query.

Have anybody experienced this before?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
update test5
   set sort_no=@srt:=if(@grp=q_id,@srt+1,1),
       q_id=@grp:=q_id
 where (0,0)=(select @grp:=0,@srt:=0)
 order by q_id, `name`

Set needed 'order by'. First column in 'order by' must be "q_id".

NOTE: before running this query, the update safe mode should be disabled (if not by default):

SET SQL_SAFE_UPDATES = 0;

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

...