Article directory
1. Create a table
grammatical format
CREATE [TEMPORARY] TABLE <表名>
(<列名1> <数据类型> [ DEFAULT‘默认值’]
[ATUO_INCREMENT] [列级完整性约束]
<列名2><数据类型>
.......
|[index_definition]
)[表设置];
[TEMPORARY] Create a temporary table
[index_definition] Specify an index for the field
simplified grammar
CREATE TABLE<表名>
(<列名1><数据类型>
<列名2><数据类型>
.......
)[表设置];
[Example 7-1] Use the command to create a student table Stu in the stuInfo database, with student number, name, gender, date of birth and major number.
USE stuInfo;
CREATE TABLE Stu
(Sno char(6) NOT NULL,
Sname varchar(4),
Ssex Enum('男','女'),
Sbirth date,
Zno varchar(4)
);
2. View table
Display the table names in the current database
SHOW TABLES;
show the structure of the specified table
DESC [RIBE] table name;
SHOW CREATE TABLE table name;
3. Modify the table
The ALTER TABLE <table name> statement is used to add, modify or delete columns in an existing table.
ALTER TABLE <表名>
[ADD <列定义> [first|after列名]
|[MODIFY <列定义> [first | after 列名]]
|[DROP <列名>]
|[CHANGE <旧列名> <新列名> <新数据类型>]
|[RENAME <新表名>]
|[ORDER BY <列名>]
[Example 7-9] Insert an attribute scollege after Sbrith in the stu data table, the length is 20, and it is allowed to be empty.
add column
ALTER TABLE stu
ADD scollege char(20);
empty is not allowed
ALTER TABLE stu
ADD scollege char(20) not null;
after the sbirth column
ALTER TABLE stu
ADD scollege char(20) not null after sbirth;
[Example 7-6] Change the attribute scollege to a length of 10 and put it in the first column
ALTER TABLE stu
MODIFY scollege char(10) first;
[Example 7-10] Delete the college column.
ALTER TABLE stu
drop scollege;
4. Copy table
grammatical format
CREATE [temporary] TABLE <表名>
[like 源表名] | [as (select 语句)];
[Example 7-15] Copy the stu table to stu1. Do not copy data, only copy structure
CREATE TABLE stu1
LIKE stu;
[Example 7-16] Copy the sno and sname in the stu table to stu2. copy data
CREATE TABLE stu2
AS
SELECT sno,sname FROM stu;
5. Delete table
grammatical format
DROP TABLE [IF EXISTS]<表名>
6. Matters needing attention in table management
1. Empty value NULL
Indicates unknown, unavailable, or data that will be added later, which is different from the number 0 or the null character.
2. The flag (IDENTITY) attribute of the column
Any table can create a flag column, and the ordinal value is generated by the system. The serial number value uniquely identifies a row in the table and can be used as a key value.
3. Implicit changes to column types
In MySQL, the system implicitly changes the column types specified in the table. VARCHAR type with length less than 4 will be changed to CHAR type.