This article records in detail how to modify the MySQL table structure through commands, such as adding columns, deleting columns, etc.; not only have you learned, you have also learned, and you can collect ashes~
-
before the start
The previous article created some tables, and the ER diagram is as follows. This article
score
operates on the table, the scene is to add a new备注remarks
field, the data type isvarchar
, the length1000
is allowednull
, and the default value is无
;
View table structure
To view the detailed design information of a specific table in the MySQL database, you can use DESCRIBE
the command, which can display information such as the name, data type, default value, null constraint, and key constraint of all columns in the table. For example:
- View the structure of the score table
mysql> describe score;
+------------+--------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| student_id | int | NO | MUL | NULL | |
| course_id | int | NO | MUL | NULL | |
| score | double | NO | | NULL | |
+------------+--------+------+-----+---------+----------------+
4 rows in set (0.01 sec)
Enter the command
describe score;
to displayscore
all the fields of the table, as well as the corresponding name, data type, default value, null value constraint, key constraint and other information of each field;MUL here
Key
is mainly because these two fields have foreign key constraints, which are constrained to correspond to the corresponding fields of another table;
- View the structure of a column of a table
mysql> describe score id;
+-------+------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
+-------+------+------+-----+---------+----------------+
1 row in set (0.00 sec)
Enter
describe score id;
to viewscore
the structural information of the id column of the table; the usage isdescribe 表名 列名;
Here you can also use show columns to view the structure :
View a table structure:SHOW COLUMNS FROM table_name;
View the structure of a field in a table:SHOW COLUMNS FROM table_name LIKE 'column_name';
add column
Following the above scenario, add a new 备注remarks
field to the score table, the data type is varchar
, the length 1000
is allowed null
, and the default value is 无
;
mysql> ALTER TABLE score ADD remarks VARCHAR(1000) NULL DEFAULT '无';
Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0
The above command completes the insertion of the data column; let's look at the table structure after adding the column:
mysql> describe score;
+------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| student_id | int | NO | MUL | NULL | |
| course_id | int | NO | MUL | NULL | |
| score | double | NO | | NULL | |
| remarks | varchar(1000) | YES | | 无 | |
+------------+---------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)
As above, our scenario requirements are completed;
Among them, the new command
ALTER TABLE
is used to modify the table structure,score
which is the name of the table to be modified,ADD remarks
indicating that aremarks
column named is added,VARCHAR(1000)
indicating that the data type isvarchar
, and the length is1000
,NULL
indicating that the column is allowed to benull
, andDEFAULT '无'
indicating the default value无
.
modify column
Here, the value of modifying the comment column is not allowed to be empty, and the default value 空备注
is the scene;
mysql> alter table score modify column remarks varchar(1000) not null default '无备注';
Query OK, 0 rows affected (0.08 sec)
Records: 0 Duplicates: 0 Warnings: 0
Use alter table score modify column remarks varchar(1000) not null default '无备注';
it to complete our requirements, the changed structure:
mysql> describe score;
+------------+---------------+------+-----+-----------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------+------+-----+-----------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| student_id | int | NO | MUL | NULL | |
| course_id | int | NO | MUL | NULL | |
| score | double | NO | | NULL | |
| remarks | varchar(1000) | NO | | 无备注 | |
+------------+---------------+------+-----+-----------+----------------+
5 rows in set (0.00 sec)
Command format:
ALTER TABLE table_name MODIFY COLUMN column_name column_type NOT NULL DEFAULT '默认值';
table_name
Indicates the name of the table that needs to be modified,column_name
the name of the column that needs to be modified,column_type
the original data type of the column,NOT NULL
the setting of the column as a non-null constraint,DEFAULT '默认值'
and the setting of the default value of the column默认值
.Note :
column_type
is required. In SQL, modifying the data type of a column in a table is an important operation, because the data type determines the type and range of data that the column can store. If you do not specify the data type, MySQL cannot parse the statement, and an error occurs:mysql> alter table score modify column remarks not null default '无备注'; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'not null default '无备注'' at line 1
duplicated column
Here rename remarks to new_remarks;
mysql> alter table score rename column remarks TO new_remarks;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
Effect:
mysql> describe score;
+-------------+---------------+------+-----+-----------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+-----------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| student_id | int | NO | MUL | NULL | |
| course_id | int | NO | MUL | NULL | |
| score | double | NO | | NULL | |
| new_remarks | varchar(1000) | NO | | 无备注 | |
+-------------+---------------+------+-----+-----------+----------------+
5 rows in set (0.01 sec)
Command usage:
ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name;
table_name
Indicates the name of the table that needs to be operated,old_column_name
the name of the column that needs to be renamed,new_column_name
and the new column name, and the keyword isRENAME
;
change column position
This scenario is very simple, that is, to change the position of the comment column, but due to the reason of SQL syntax, what needs to be distinguished is that the command to move to the back of a certain column or to the beginning of the table is different;
mysql> ALTER TABLE score MODIFY COLUMN new_remarks varchar(1000) AFTER student_id;
Query OK, 0 rows affected (0.09 sec)
Records: 0 Duplicates: 0 Warnings: 0
This is the command after moving to a certain column, the effect is as follows:
mysql> describe score;
+-------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| student_id | int | NO | MUL | NULL | |
| new_remarks | varchar(1000) | YES | | NULL | |
| course_id | int | NO | MUL | NULL | |
| score | double | NO | | NULL | |
+-------------+---------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
Here is the command to move to the header:
mysql> alter table score modify column new_remarks varchar(1000) first;
Query OK, 0 rows affected (0.12 sec)
Records: 0 Duplicates: 0 Warnings: 0
The effect after moving:
mysql> describe score;
+-------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+----------------+
| new_remarks | varchar(1000) | YES | | NULL | |
| id | int | NO | PRI | NULL | auto_increment |
| student_id | int | NO | MUL | NULL | |
| course_id | int | NO | MUL | NULL | |
| score | double | NO | | NULL | |
+-------------+---------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)
Command after moving to a column:
ALTER TABLE table_name MODIFY COLUMN column_name column_definition AFTER other_column_name;
table_name
Indicates the name of the table that needs to be operated,column_name
indicates the name of the column that needs to be changed, andcolumn_definition
indicates the column definition, which can include information such as data type, default value, etc.AFTER
The keyword is followed by which column the column needs to be placed, andother_column_name
it is the column of other columns name.Move to the very beginning:
ALTER TABLE table_name MODIFY COLUMN column_name column_definition FIRST;
table_name
It is the name of the table to be operated,column_name
the name of the column to be moved,column_definition
and the definition of the column,FIRST
indicating that the column will be moved to the beginning of the table.Note :
- When using
ALTER TABLE
the command to modify a column, if the data type is omitted, an error will be reported because a new data type must be specified. That is, the above command cannot omitvarchar(1000)
fields;- In MySQL,
LAST
is not a legal keyword and will cause a syntax error. To move a column to the end of the table, useAFTER
the keyword to specify the name of the column to move the column to. That is:alter table score modify column new_remarks varchar(1000) LAST;
it is a wrong statement!
delete column
Here we delete the newly created comment field:
mysql> alter table score drop column new_remarks;
Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0
After deleting, the original effect is restored:
mysql> describe score;
+------------+--------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| student_id | int | NO | MUL | NULL | |
| course_id | int | NO | MUL | NULL | |
| score | double | NO | | NULL | |
+------------+--------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
We used
DROP COLUMN
a clause to indicate that the column should be dropped. Note that this permanently removes the column from the table!
Q&A
What does Extra in the table structure mean?
The Extra field in the MySQL table structure is used to display additional information and comments. This field provides some important information, such as self-increment, default value, primary key information, etc. It can tell the user more about the column and help the user better understand the role and purpose of the column.
Common Extra field values include:
- auto_increment: Indicates that the column is an auto-increment primary key.
- on update CURRENT_TIMESTAMP: Indicates that the column is set to automatically update the timestamp function.
- DEFAULT 'xxx': Indicates that the column has a default value of xxx.
What does the key of the table structure represent?
PRI
: Indicates that the column is the primary key, which is a special index used to uniquely identify each row of data in the table. Each table can have at most one primary key, and the data in the primary key restriction table cannot be duplicated and cannot be NULL.MUL
: Non-unique index, when the index includes multiple duplicate key values, the Key attribute value will be displayed asmul
.UNI
: Indicates that the column is a unique key. A unique key can also be used to uniquely identify each row of data in a table, but it allows NULL values. A table can have multiple unique keys.FULLTEXT
: Indicates that the column is a full-text index. Full-text indexing is used to optimize full-text searches, such as keyword searches on article titles and text. A table can have at most one full-text index.- `` (null): Indicates that the column is neither a primary key nor a unique key.
For example, when
DESCRIBE
viewing astudents
table named with the command, you might get the following output:mysql> DESCRIBE students; +----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(50) | YES | | NULL | | | gender | char(1) | YES | | NULL | | | age | int(11) | YES | | NULL | | | email | varchar(80) | YES | UNI | NULL | | | address | varchar(100)| YES | | NULL | | +----------+-------------+------+-----+---------+-------+
Among them,
id
the columnKey
isPRI
, indicating that it is a primary key;Key
isUNI
, indicating that it is a unique key; the other columnsKey
are""
(empty), indicating that they are neither primary keys nor unique keys.
what is index
A MySQL index is a data structure that helps MySQL quickly obtain data, just like the catalog of a book can quickly access specific information. It can improve the speed of database queries. The basic principle is to trade space for time, and store indexes in files on disk to speed up reading and writing. Indexes allow you to quickly access specific information in a table by sorting the values of one or more columns in the table. The realization of the index depends on the design of the storage engine and the data retrieval engine of the database, so choosing an appropriate data structure can improve the performance of data retrieval, and for a database with large-scale data storage, it is very important to select an appropriate and efficient search algorithm.
- Primary key index: The values in the indexed column must be unique, and null values are not allowed.
- Ordinary index: The basic index type in MySQL, there are no restrictions, and it is allowed to insert duplicate values and null values in the columns defining the index.
- Unique index: The values in the indexed column must be unique, but null values are allowed.
- Full-text index: Full-text indexes can only be created on fields of text type CHAR, VARCHAR, and TEXT. When the field length is relatively large, if you create an ordinary index, the efficiency is relatively low when performing like fuzzy queries. At this time, you can create a full-text index. Full-text indexes are available in both MyISAM and InnoDB.
- Spatial index: MySQL version after 5.7 supports spatial index, and supports OpenGIS geometric data model. MySQL follows the OpenGIS geometric data model rules for spatial indexes.
- Prefix index: When creating an index on a text type column such as CHAR, VARCHAR, and TEXT, the length of the index column can be specified, but the value type cannot be specified.
- Others (classified by the number of index columns)
- single column index
- Composite index: The use of composite index needs to follow the leftmost prefix matching principle (leftmost matching principle). Generally, composite indexes are used instead of multiple single-column indexes when conditions permit.
How to view the indexes in a table
SHOW INDEX FROM score;
Here is an explanation of these fields:
- Table: The name of the table where the index resides.
- Non_unique: Whether the index allows duplicate values, 0 indicates a unique index, and 1 indicates that duplicate values are allowed.
- Key_name: The name of the index.
- Seq_in_index: The order of the column in the index, starting from 1.
- Column_name: The column name included in the index.
- Collation: The character set collation to use for this column, or NULL if the column is not in any index.
- Cardinality: An estimate of the number of unique values in the index, not necessarily accurate.
- Sub_part: If it is a prefix index, it indicates the length of the indexed string, otherwise it is NULL.
- Packed: If it is a PACK_KEYS index type, it indicates the compression rate used, otherwise it is NULL.
- Null: Whether the column allows NULL values, if allowed, it is YES, otherwise it is NO.
- Index_type: Index type, such as Btree, Hash, etc.
- Comment: A comment for the index.
- Index_comment: The character set and collation of index comments.
- Visible: Whether the index is visible, 0 means hidden, 1 means visible.
- Expression: The expression or function name if this index is the result of a function or expression, otherwise NULL.
How to view the constraints of a table
mysql> SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE -> FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS -> WHERE TABLE_SCHEMA = 'student_score_db' and table_name='score'; +------------------+-----------------+ | CONSTRAINT_NAME | CONSTRAINT_TYPE | +------------------+-----------------+ | PRIMARY | PRIMARY KEY | | fk_score_course | FOREIGN KEY | | fk_score_student | FOREIGN KEY | +------------------+-----------------+ 3 rows in set (0.00 sec)
The above SQL statement will return all constraint names and types for the given table, such as
PRIMARY KEY、FOREIGN KEY、UNIQUE
etc. If you want to see the details of a specific constraint (such as the columns included), you can useINFORMATION_SCHEMA.KEY_COLUMN_USAGE
the table to query.
Original link: https://blog.jiumoz.com/archives/sql-bi-ji-2mysql-de-biao-cao-zuo-yu-suo-yin