简体   繁体   中英

How to change the column position of MySQL table without losing column data?

I want to change the column positions of my database table without losing data.

For example:

Current table:

+----+------+-------+----------+
| id | name | email | password |
+----+------+-------+----------+

to

+----+----------+------+-------+
| id | password | name | email |
+----+----------+------+-------+

试试这个:

ALTER TABLE table_name MODIFY password varchar(20) AFTER id

Hearaman's answer is correct; but if you are using phpMyAdmin, there is a visual and practical way to do that.

  1. Open the table
  2. Choose the " Structure " tab
  3. Click on " Move columns "
  4. Drag and drop column names

移动列链接,结构选项卡中间 移动列弹出窗口

If you are using MySQL workbench,

  1. Right-click on table
  2. Alter table
  3. drag columns and re-order
  4. click apply and finish

此外,你可以这样做:

ALTER TABLE table_name CHANGE COLUMN column_name column_name data_type AFTER another_column_name;

You can use modify/change keyword.

ALTER TABLE [table] CHANGE COLUMN [column] [column] [column definition] AFTER [column]

ALTER TABLE [table] MODIFY COLUMN [column] [column definition] AFTER [column]

Eg:

ALTER TABLE table_name MODIFY password varchar(20) AFTER id

ALTER TABLE table_name MODIFY password varchar(20) varchar(20) AFTER id

Another method if you are using MySQLWorkbench,

  • On your top right, click Schemas
  • find and select your database, then find and select the table you want to modify
  • When you hover over the table you would see three icons, click on settings (that is the one in the middle),
  • then click on the column and drag it to the position you want your column to be.
  • on your bottom right you will see apply (click and apply🙂).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM