Methods to modify mysql database tables: Use the "ALTER TABLE" statement to change the structure of the original table, such as adding fields or deleting fields, modifying the original field data type, renaming fields or tables, modifying Table character set, etc.; syntax "ALTER TABLE
[modify options]".
#The prerequisite for modifying the data table is that the table already exists in the database. Modifying a table refers to modifying the structure of an existing data table in the database. The operation of modifying the data table is also essential in database management. It is just like drawing a sketch. If you draw too much, you can erase it with an eraser. If you draw too little, you can add it with a pen.
Not knowing how to modify the data table is equivalent to throwing away and redrawing as long as we make a mistake, which increases unnecessary costs.
In MySQL, you can use the
ALTER TABLEstatement to change the structure of the original table, such as adding or deleting columns, changing the original column type, renaming columns or tables, etc.The syntax format is as follows:
ALTER TABLE <表名> [修改选项]The syntax format for modifying options is as follows:
{ ADD COLUMN <列名> <类型> | CHANGE COLUMN <旧列名> <新列名> <新列类型> | ALTER COLUMN <列名> { SET DEFAULT <默认值> | DROP DEFAULT } | MODIFY COLUMN <列名> <类型> | DROP COLUMN <列名> | RENAME TO <新表名> | CHARACTER SET <字符集名> | COLLATE <校对规则名> }Modify the table name
MySQL uses the ALTER TABLE statement to modify the table name. The syntax rules are as follows:
ALTER TABLE <旧表名> RENAME [TO] <新表名>;Among them, TO is an optional parameter, and whether it is used or not does not affect the result.
Example 1
Use ALTER TABLE to rename the data table student to tb_students_info. The SQL statement and running results are as follows.
mysql> ALTER TABLE student RENAME TO tb_students_info; Query OK, 0 rows affected (0.01 sec) mysql> SHOW TABLES; +------------------+ | Tables_in_test | +------------------+ | tb_students_info | +------------------+ 1 row in set (0.00 sec)Tip: Modifying the table name does not modify the structure of the table, so the structure of the table after the name is modified is the same as that of the table before the name was modified. Users can use the DESC command to view the modified table structure,
Modify the table character set
MySQL implements the table character set through the ALTER TABLE statement Modification, the syntax rules are as follows:
ALTER TABLE 表名 [DEFAULT] CHARACTER SET <字符集名> [DEFAULT] COLLATE <校对规则名>;Among them, DEFAULT is an optional parameter, and whether it is used or not will not affect the result.
Example 2
Use ALTER TABLE to modify the character set of the data table tb_students_info to gb2312 and the collation rule to gb2312_chinese_ci. The SQL statement and running results are shown below.
mysql> ALTER TABLE tb_students_info CHARACTER SET gb2312 DEFAULT COLLATE gb2312_chinese_ci; Query OK, 0 rows affected (0.08 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> SHOW CREATE TABLE tb_students_info \G *************************** 1. row *************************** Table: tb_students_info Create Table: CREATE TABLE `tb_students_info` ( `id` int(11) NOT NULL, `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=gb2312 1 row in set (0.00 sec)MySQL data table adding fields
MySQL data table is composed of rows and columns. The "columns" of the table are usually called Field (Field) refers to the "row" of the table as a record (Record). As your business changes, you may need to add new fields to existing tables.
MySQL allows adding fields at the beginning, middle and end.
Add fields at the end
A complete field includes field name, data type and constraints. The syntax format for adding fields in MySQL is as follows:
ALTER TABLE <表名> ADD <新字段名><数据类型>[约束条件];The syntax format is explained as follows:
is the name of the data table;
is the name of the field to be added; is the field that can store data Data type;
[Constraints] is optional and is used to constrain the added fields.
This syntax format adds a new field at the last position of the table (after the last column) by default.
Note: In this section we only add new fields and do not pay attention to its constraints.
Example
Create a new student data table in the test database. The SQL statements and running results are as follows:
mysql> USE test; Database changed mysql> CREATE TABLE student ( -> id INT(4), -> name VARCHAR(20), -> sex CHAR(1)); Query OK, 0 rows affected (0.09 sec)Use DESC to view the student table structure. The SQL statements and running results are as follows:
mysql> DESC student; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | id | int(4) | YES | | NULL | | | name | varchar(20) | YES | | NULL | | | sex | char(1) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 3 rows in set (0.01 sec)Use the ALTER TABLE statement to add an INT type field age. The SQL statement and running results are as follows:
mysql> ALTER TABLE student ADD age INT(4); Query OK, 0 rows affected (0.16 sec) Records: 0 Duplicates: 0 Warnings: 0Use DESC to view the student table structure and verify whether the age field is added successfully. The SQL statement and running results are as follows:
mysql> DESC student; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | id | int(4) | YES | | NULL | | | name | varchar(20) | YES | | NULL | | | sex | char(1) | YES | | NULL | | | age | int(4) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 4 rows in set (0.00 sec)As you can see from the running results, the age field has been added to the student table, and the field is at the last position of the table. The field was added successfully.
Add a field at the beginning
MySQL adds a new field at the last position of the table by default. If you want to add a new field at the beginning (before the first column), then You can use the FIRST keyword, the syntax format is as follows:
ALTER TABLE <表名> ADD <新字段名> <数据类型> [约束条件] FIRST;The FIRST keyword is generally placed at the end of the statement.
Example
Use the ALTER TABLE statement to add the INT type field stuId in the first column of the table. The SQL statement and running results are as follows.
mysql> ALTER TABLE student ADD stuId INT(4) FIRST; Query OK, 0 rows affected (0.14 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESC student; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | stuId | int(4) | YES | | NULL | | | id | int(4) | YES | | NULL | | | name | varchar(20) | YES | | NULL | | | sex | char(1) | YES | | NULL | | | age | int(4) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 5 rows in set (0.00 sec)You can see from the running results that the stuId field has been added to the student table, and the field is at the first position in the table. The field was added successfully.
Add fields in the middle position
In addition to allowing fields to be added at the beginning and end of the table, MySQL also allows adding fields in the middle position (after the specified field) Field, you need to use the AFTER keyword at this time, the syntax format is as follows:
ALTER TABLE <表名> ADD <新字段名> <数据类型> [约束条件] AFTER <已经存在的字段名>;The function of AFTER is to add a new field after an existing field.
Note that you can only add a new field after an existing field, but not in front of it.
Example
使用 ALTER TABLE 语句在 student 表中添加名为 stuno,数据类型为 INT 的字段,stuno 字段位于 name 字段的后面。SQL 语句和运行结果如下:
mysql> ALTER TABLE student ADD stuno INT(11) AFTER name; Query OK, 0 rows affected (0.13 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESC student; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | stuId | int(4) | YES | | NULL | | | id | int(4) | YES | | NULL | | | name | varchar(20) | YES | | NULL | | | stuno | int(11) | YES | | NULL | | | sex | char(1) | YES | | NULL | | | age | int(4) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 6 rows in set (0.00 sec)由运行结果可以看到,student 表中已经添加了 stuId 字段,且该字段在 name 字段后面的位置,添加字段成功。
MySQL 修改和删除数据表字段
修改字段名称
MySQL 中修改表字段名的语法规则如下:
ALTER TABLE <表名> CHANGE <旧字段名> <新字段名> <新数据类型>;其中:
旧字段名:指修改前的字段名;
新字段名:指修改后的字段名;
新数据类型:指修改后的数据类型,如果不需要修改字段的数据类型,可以将新数据类型设置成与原来一样,但数据类型不能为空。
例
使用 ALTER TABLE 修改表 tb_emp1 的结构,将 col1 字段名称改为 col3,同时将数据类型变为 CHAR(30),SQL 语句和运行结果如下所示。
mysql> ALTER TABLE tb_emp1 -> CHANGE col1 col3 CHAR(30); Query OK, 0 rows affected (0.76 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESC tb_emp1; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | col3 | char(30) | YES | | NULL | | | id | int(11) | YES | | NULL | | | name | varchar(30) | YES | | NULL | | | deptId | int(11) | YES | | NULL | | | salary | float | YES | | NULL | | +--------+-------------+------+-----+---------+-------+ 5 rows in set (0.01 sec)CHANGE 也可以只修改数据类型,实现和 MODIFY 同样的效果,方法是将 SQL 语句中的“新字段名”和“旧字段名”设置为相同的名称,只改变“数据类型”。
提示:由于不同类型的数据在机器中的存储方式及长度并不相同,修改数据类型可能会影响数据表中已有的数据记录,因此,当数据表中已经有数据时,不要轻易修改数据类型。
修改字段数据类型
修改字段的数据类型就是把字段的数据类型转换成另一种数据类型。在 MySQL 中修改字段数据类型的语法规则如下:
ALTER TABLE <表名> MODIFY <字段名> <数据类型>其中:
表名:指要修改数据类型的字段所在表的名称;
字段名:指需要修改的字段;
数据类型:指修改后字段的新数据类型。
例
使用 ALTER TABLE 修改表 tb_emp1 的结构,将 name 字段的数据类型由 VARCHAR(22) 修改成 VARCHAR(30),SQL 语句和运行结果如下所示。
mysql> ALTER TABLE tb_emp1 -> MODIFY name VARCHAR(30); Query OK, 0 rows affected (0.15 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESC tb_emp1; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | col1 | int(11) | YES | | NULL | | | id | int(11) | YES | | NULL | | | name | varchar(30) | YES | | NULL | | | col2 | int(11) | YES | | NULL | | | deptId | int(11) | YES | | NULL | | | salary | float | YES | | NULL | | +--------+-------------+------+-----+---------+-------+ 6 rows in set (0.00 sec)语句执行后,发现表 tb_emp1 中 name 字段的数据类型已经修改成 VARCHAR(30),修改成功。
删除字段
删除字段是将数据表中的某个字段从表中移除,语法格式如下:
ALTER TABLE <表名> DROP <字段名>;其中,“字段名”指需要从表中删除的字段的名称。
例
使用 ALTER TABLE 修改表 tb_emp1 的结构,删除 col2 字段,SQL 语句和运行结果如下所示。
mysql> ALTER TABLE tb_emp1 -> DROP col2; Query OK, 0 rows affected (0.53 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESC tb_emp1; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | col1 | int(11) | YES | | NULL | | | id | int(11) | YES | | NULL | | | name | varchar(30) | YES | | NULL | | | deptId | int(11) | YES | | NULL | | | salary | float | YES | | NULL | | +--------+-------------+------+-----+---------+-------+ 5 rows in set (0.00 sec)推荐教程:mysql视频教程
The above is the detailed content of How to modify mysql database table?. For more information, please follow other related articles on the PHP Chinese website!
MySQL's Role: Databases in Web ApplicationsApr 17, 2025 am 12:23 AMThe main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.
MySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AMThe steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.
MySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AMMySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.
Is MySQL Beginner-Friendly? Assessing the Learning CurveApr 17, 2025 am 12:19 AMMySQL is suitable for beginners because: 1) easy to install and configure, 2) rich learning resources, 3) intuitive SQL syntax, 4) powerful tool support. Nevertheless, beginners need to overcome challenges such as database design, query optimization, security management, and data backup.
Is SQL a Programming Language? Clarifying the TerminologyApr 17, 2025 am 12:17 AMYes,SQLisaprogramminglanguagespecializedfordatamanagement.1)It'sdeclarative,focusingonwhattoachieveratherthanhow.2)SQLisessentialforquerying,inserting,updating,anddeletingdatainrelationaldatabases.3)Whileuser-friendly,itrequiresoptimizationtoavoidper
Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Apr 16, 2025 am 12:20 AMACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.
MySQL: Database Management System vs. Programming LanguageApr 16, 2025 am 12:19 AMMySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.
MySQL: Managing Data with SQL CommandsApr 16, 2025 am 12:19 AMMySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment







