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

sql - How to sort values in columns and update table?

I'm completely new to sql and can't do that myself. So I need your help. I want to sort values in column and then save changes. But I don't know how to do that.

Table looks like that:

Id | Name | SomeDescription
---------------------------
1  |Best  | Description1
2  |Worth | Description2
3  |Good  | Description3

I want to get something like that:

Id | Name | SomeDescription
---------------------------
1  |Best  | Description1
2  |Good  | Description3
3  |Worth | Description2

So I need to sort "id" and "name" columns.

I use following statement to sort values of "name" column:

SELECT * FROM games ORDER BY name ASC

But how can I sort the values of id column and save changes in table? Please, help.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You would have to use a second table

  1. create a new table games2 with the same structure as your games table, making sure the ID is auto-incrementing

    CREATE TABLE `games2` LIKE `games`;
    
  2. copy the data, sorted, into games2

    INSERT INTO `games2` (`Name`, `SomeDescription`) SELECT `Name`, `SomeDescription` FROM `games` ORDER BY `Name`
    
  3. drop or move the old table

    -- DROP TABLE `games`;
    -- or
    RENAME TABLE `games` TO `games1`;
    
  4. rename new table to old name

    RENAME TABLE `games2` TO `games`;
    

These steps will result in what you want.


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

...