Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Thay đổi vị trí cột trong MySQL mà không mất dữ liệu?

Sử dụng ALTER TABLE ... MODIFY COLUMN ten_cot kieu_du_lieu AFTER ten_cot_khac.

Cú pháp:

ALTER TABLE ten_bang MODIFY ten_cot_1 kieu_du_lieu AFTER ten_cot_2;

Ví dụ: Bảng gốc có thứ tự: StudentId, StudentAddress, StudentAge, StudentName. Muốn đưa StudentAddress ra sau StudentAge.

CREATE TABLE changeColumnPositionDemo (
    StudentId INT, StudentAddress VARCHAR(200), StudentAge INT, StudentName VARCHAR(200)
);
INSERT INTO changeColumnPositionDemo VALUES
(101,'US',23,'Johnson'), (102,'UK',20,'John'), (103,'US',22,'Carol'), (104,'UK',19,'Sam');

Thứ tự ban đầu:

+-----------+----------------+------------+-------------+
| StudentId | StudentAddress | StudentAge | StudentName |
+-----------+----------------+------------+-------------+
|       101 | US             |         23 | Johnson     |
|       102 | UK             |         20 | John        |
|       103 | US             |         22 | Carol       |
|       104 | UK             |         19 | Sam         |
+-----------+----------------+------------+-------------+

Di chuyển cột:

ALTER TABLE changeColumnPositionDemo MODIFY StudentAddress VARCHAR(200) AFTER StudentAge;

Kết quả (thứ tự mới: Id, Age, Address, Name)

+-----------+------------+----------------+-------------+
| StudentId | StudentAge | StudentAddress | StudentName |
+-----------+------------+----------------+-------------+
|       101 |         23 | US             | Johnson     |
|       102 |         20 | UK             | John        |
|       103 |         22 | US             | Carol       |
|       104 |         19 | UK             | Sam         |
+-----------+------------+----------------+-------------+

Lưu ý: Dữ liệu không bị mất. MySQL rebuild bảng ngầm. Cũng có thể dùng FIRST để đưa lên đầu. MySQL 8.0+ hỗ trợ ALTER TABLE ... RENAME COLUMN nhưng không đổi vị trí.