--1.创建表(类似于一个excel表)
create tabletab_name(
field1 type[完整性约束条件],
field2 type,
...
fieldn type
)[character set xxx];--创建一个员工表employee
create tableemployee(
idint primary keyauto_increment ,
namevarchar(20),
genderbit default 1, --gender char(1) default 1 ----- 或者 TINYINT(1)
birthday date,
entry_date date,
jobvarchar(20),
salarydouble(4,2) unsigned,
resumetext --注意,这里作为最后一个字段不加逗号
);/*约束:
primary key (非空且唯一) :能够唯一区分出当前记录的字段称为主键!
unique
not null
auto_increment 主键字段必须是数字类型。
外键约束 foreign key*/
--2.查看表信息
desctab_name 查看表结构
show columnsfromtab_name 查看表结构
show tables 查看当前数据库中的所有的表
showcreate tabletab_name 查看当前数据库表建表语句--3.修改表结构
--(1)增加列(字段)
alter table tab_name add [column]列名 类型[完整性约束条件][first|after 字段名];alter table user add addr varchar(20) not null unique first/after username;
#添加多个字段alter tableusers2add addr varchar(20),add age intfirst,add birth varchar(20) after name;--(2)修改一列类型
alter table tab_name modify 列名 类型 [完整性约束条件][first|after 字段名];alter table users2 modify age tinyint default 20;alter table users2 modify age intafter id;--(3)修改列名
alter table tab_name change [column] 列名 新列名 类型 [完整性约束条件][first|after 字段名];alter table users2 change age Age int default 28first;--(4)删除一列
alter table tab_name drop [column]列名;--思考:删除多列呢?删一个填一个呢?
alter tableusers2add salary float(6,2) unsigned not nullafter name,dropaddr;--(5)修改表名
rename table 表名 to新表名;--(6)修该表所用的字符集
alter table student character setutf8;--4.删除表
drop tabletab_name;---5 添加主键,删除主键
alter table tab_name add primary key(字段名称,...)alter table users drop primary key;
eg:
mysql> create table test5(num intauto_increment);
ERROR1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
create table test(num int primary keyauto_increment);--思考,如何删除主键?
alter table test modify id int; --auto_increment没了,但这样写主键依然存在,所以还要加上下面这句
alter table test drop primary key;--仅仅用这句也无法直接删除主键
--唯一索引
alter table tab_name add unique [index|key] [索引名称](字段名称,...)alter table users add unique(name)--索引值默认为字段名show create table users;
alter table users add unique key user_name(name);--索引值为user_name
--添加联合索引
alter table users add unique index name_age(name,age);#show create tableusers;--删除唯一索引
alter table tab_name drop {index|key} index_name