Create table
create table 表名(
列名 列的类型(长度) 约束;
列名2 列的类型(长度) 约束
);
Take any column name ;
column type:
java | sql |
---|---|
int | int() |
char/string | char()/varchar() char (fixed length), varchar (variable length) |
double | double() |
float | float() |
boolean | N/A |
date | date():YYYY-MM-DD |
time():hh:mm:ss | |
datetime():YYYY-MM-DD hh:mm:ss default value is null | |
timestamp():YYYY-MM-DD hh:mm:ss uses the current time by default | |
text is mainly used to store text | |
blob: Stored in binary |
Column constraints:
- Primary key constraint: primary key (pk_xxx)
- Unique constraint: unique (uq_xxx)
- Non-empty constraint: not null
- Foreign key constraint: foreign key (fk_xxx)
- Conditional constraints: check (chk_xxx)
- Default constraint: default (df_xxx)
Create table:
1. Analyze entity: student
create table student(
sid int primary key,
sname varchar(6),
sex char(1),
age int
);
View all tables:
show tables;
View the definition of the table:
show create table 表名;
如:show create table day06;
View table structure:
desc 表名;
如:desc student;
Modify the table:
add column (add), modify column (modify), modify column name (change), delete column (drop), modify table name (remane), modify table character set (default character)
添加列(add):
alter table 表名 add 列名 列的类型 列的约束;
如:alter table student add changji int not null;
修改列(modify):
alter table 表名 modify 列名 新列的类型 列的约束;
如:alter table student modify ssex varchar(2);
修改列名(change):
alter table 表名 change 旧列名 新列名 列的类型 列的约束;
如:alter table student change ssex gender varchar(2);
删除列(drop):
alter table 表名 drop 列名;
如:alter table student drop chengji;
修改表名(remane):
rename table 旧表名 to 新表名;
如:rename table student to heima;
修改表的字符集(default character):
alter table 表名 character set 新字符集;
如:alter table student character set gbk;
Delete table:
drop table 表名;
如:drop table heima;