1.显示当前使用的数据库中所有表:
show tables;
2.创建表
create table 表名(
列名 类型 ,
列名 类型
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
在创建表的同时还可以规定:
是否为空
not null
null
设置每列的默认值
defalut 1
设置列的自增
auto_increment
自增必须设置到索引列中
自增可以设置起始值和步长
set id auto_increment_increment=2;--起始值
set id auto_increment_offset=2;--步长
主键
primary key
外键
将表的一列与另一张表的一列相关联,使这一列的内容只能是相关联的那一列的内容
constraint 外键名 foreign key (本表的某列) references color(其他表的某列);
举例
create table student(
sid int not null auto_increment primary key,
course_id int not null defalut 1,
constraint fk_sc foreign key (course_id) references course(cid)
);
3.删除表
drop table 表名;
4.清空表
delete from 表名 --不会删除自增的数量,根据之前的自增序号继续自增
truncate table 表名
5.修改表
添加列:alter table 表名 add 列名 类型;
删除列:alter table 表名 drop column 列名;
修改列:
alter table 表名 modify column 列名 类型; --修改类型
alter table 表名 change 原列名 新列名 类型;
添加主键:
alter table 表名 add primary key(列名);
删除主键:
alter table 表名 drop primary key;
alter table 表名 modify 列名 类型, drop primary key;
添加外键:alter table 本表 add constraint 外键名称 foreign key 本表外键列 references 引用外键表列;
删除外键:alter table 表名 drop foreign key 外键名称
alter table 表名modify 字段名default 默认值
修改默认值:alter table 表名modify 字段名default 默认值;
删除默认值:ALTER TABLE 表名 ALTER COLUMN 列名 DROP DEFAULT;
6.基本数据类型
bit 二进制
tinyint -128 ~ 127
int -2147483648 ~ 2147483647
bigint -9223372036854775808 ~ 9223372036854775807
decimal 精确的小数
float 0 1.175494351E-38 to 3.402823466E+38
double 0 2.2250738585072014E-308 to 1.7976931348623157E+308
char (m) 固定长度的字符串,m为固定长度,最大为255
varchar(m) 非固定长度的字符串,m为最大长度 最大为255
text 保存变长的长字符串,可以最多到65535
mediumtext 最多2**24 − 1
longtext 最多2**32 − 1
enum 枚举类型,如season ENUM('spring', 'summer', autumn', 'winter')
set 集合类型,如myset set('a', 'b', 'c', 'd'),集合类型可以是集合中的组合('a,b,c')
date YYYY-MM-DD
time HH:MM:SS
year YYYY
DATETIME YYYY-MM-DD HH:MM:SS
TIMESTAMP
7.索引
索引可以加速查询,使用B+Tree实现其索引结构。
普通索引:
创建表时创建索引
create table name(
nid int not null ,
index 索引名 (nid)
);
添加索引
create index 索引名 on 表名(列名);
删除索引
drop 索引名 on 表名;
查看索引
show index from 表名;
唯一索引:
创建表时创建唯一索引
create table name(
nid int not null
unique 索引名(nid)
);
添加唯一索引
create unique index 索引名 on 表名(列名);
删除唯一索引
drop unique index 索引名 on 表名;
主键索引:
创建表时创建索引
create table name(
nid int not null auto_increment primary key,
index 索引名 (nid)
);
添加主键
alter table 表名 add primary key(列名);
删除主键
alter table 表名 drop primary key;
组合索引:
将多个列组合成一个索引
创建索引
create index 索引名 on 表名(列名1,列名2);
组合索引的查询是取左的方式,例如查询 列1 and 列2 ,会使用索引,查询列1会使用索引,查询列2不会使用索引。