Note: There must be a database, use the "USE database name" to specify which operations are carried out in the database, otherwise it will throw "No database selected" error data table before the operation.
For example: Create a table to store student achievement tb_grade below:
Field Name | type of data | instruction manual |
id | INT(11) | Number of students |
name | CHAR(20) | Full name |
age | INT(3) | age |
sex | CHAR(5) | gender |
To create a data table, you need to create a database, SQL statement is as follows:
CREATE DATABASE itcast;
Choose create database tables, SQL statement is as follows:
USE itcast;
First, create a data table (example: Student table)
The basic syntax:
CREATE TABLE 表名
(
Field name 1, data type [integrity constraints],
field name 2, data type [integrity constraints],
......
field name n, the data type [integrity constraints]
);
SQL statement is as follows:
CREATE TABLE student_tb
(
id INT(11),
name CHAR(20),
age INT(3),
sex CHAR(5)
);
Execution results are as follows:
View the data table is successfully created
SQL statement is as follows:
SHOW TABLES;
Execution results are as follows:
Second, view the data table
1) See definition statements and character encoding data table
The basic syntax:
SHOW CREATE TABLE 表名;
SQL statement is as follows:
SHOW CREATE TABLE student_tb;
Execution results are as follows:
2) View data table field names, field names and other types of information
The basic syntax:
DESCRIBE table name; it can be abbreviated as DESC table;
SQL statement is as follows:
DESC student_tb;
Execution results are as follows:
三、修改数据表
1)修改数据表名
基本语法:
ALTER TABLE 旧表名 RENAME [TO] 新表名;
SQL语句如下:
ALTER TABLE student_tb RENAME student_tbss;
执行结果如下:
2)修改字段名
基本语法:
ALTER TABLE 表名 CHANGE 旧字段名 新字段名 新数据类型;
SQL语句如下:
ALTER TABLE stuent_tbss CHANGE name newname CHAR(20);
执行结果如下:
字段名改变后:
3)修改字段名类型
基本语法:
ALTER TABLE 表名 MODIFY 字段名 数据类型;
SQL语句如下:
ALTER TABLE stuent_tbss MODIFY newname VARCHAR(21);
执行结果如下:
修改字段名类型后:
4)添加字段
基本语法:
ALTER TABLE 表名 ADD 新字段名 数据类型[约束条件][FIRST|AFTER 已存在字段名];
SQL语句如下:
ALTER TABLE student_tbss ADD address VARCHAR(22);
执行结果如下:
5)删除字段
基本语法:
ALTER TABLE 表名 DROP 字段名;
SQL语句如下:
ALTER TABLE student_tbss DROP sex;
执行结果如下:
删除字段后:
6)修改字段的排列位置
基本语法:
ALTER TABLE表名 MODIFY 字段名1 数据类型 FIRST|AFTER 字段名2
SQL语句如下:
ALTER TABLE student_tbss MODIFY id INT(11) AFTER address;
执行结果如下:
修改排列位置后:
四、删除数据表
基本语法:
DROP TABLE 表名;
SQL语句如下:
DROP TABLE student_tbss;
执行结果如下:
删除数据表后: