表
新建表:
create table 表名
(
字段名1 数据类型 [comment '注释'] [字段约束]
字段名2 数据类型 [comment '注释'] [字段约束]
...
);
tips: 字段约束可以为:
not NULL(不为空),primary key(主键),unique(值不能重复),AUTO_INCREMENT(添加数据时值会自动增加1),zerofill(自动填0)
更改表名:
alter table 旧表名 rename 新表名
删除表:
drop table 表名
清空表:(表内存在外键约束时无法清空)
1.truncate table 表名
2.delete from 表名
添加字段名:
alter table 表名 add [新字段名 数据类型] [约束定义] [after 已有字段名]
删除字段名:
alter table 表名 drop column 字段名
更改字段名:
alter table 表名 change 旧字段名 新字段名 新数据类型
更改字段的数据类型:
alter table 表名 modify 字段名 数据类型
调整字段的位置
alter table 表名 modify 字段名1 数据类型 first[|after 字段名2]
更改数据
update 表名 set 字段名=newValue1[,字段名2=newValue2, ... ] [where 条件表达式]
添加数据
insert into 表名 [字段名] values(值1),(值2),...
删除数据
delete from 表名 where 条件语句
添加主键
1.创建表的时候就定义主键
定义字段时添加:
字段名1 数据类型 [comment '注释'] primary key,
最后添加:
primary key(字段名1,字段名2, ...)
2.更新表时添加主键
alter table 表名 add primary key(字段名1,字段名2, ...);
添加外键
1.创建表时就添加外键
最后添加:
foreign key(外键约束的列名) references 表名(主键名)
2.更新表时添加外键
alter table 表名
add constraint 外键名
foreign key(外键约束的列名) references 表名(主键名);
删除外键
1.alter table 表名 drop constraint 约束名;
2.alter table 表名 drop foreign key 外键约束名;
查询
选择语句 select
select [distinct] 字段 [as 别名] from 表名
[limit [start,]number]
[where 条件表达式]
[group by 字段]
[having 条件表达式]
[order by 字段* [升序(asc)/降序(desc)]]
[表1 inner join 表2 on 条件表达式]
去重:
select distinct ...
使用通配符查询 like
select * from 表名 where 字段名 like "%_"
分组查询 group by
对查询结果分组,以便聚合函数汇总计算
group by 字段;
对group by 生成的分组结果进行过滤:
having condition
条件表达式
1. > < = and or <>(不等于)
2. 字段 is null
函数
count() 统计数目
max() 最大值
avg() 平均值
sum() 求和
coalesce(exp1,exp2,...,expN,default) 检查表达式1~N,返回第一个不为NULL的值,全为NULL则返回给定的默认值
round(float,dec) 将float保留dec位
concat(str1,str2,...) 将多个列连接在一起
视图
新建视图:
create view as 条件表达式
索引
创建索引:#主键创建时会自动生成索引
create [unique] index 索引名称 on 表名(字段名称1,[索引字符长度] ,字段名称2,...)
[unique] 为唯一索引 确保数据不重复
查看索引:
show index from 表名 [from 数据库名]
删除索引:
1. alter table 表名 drop index 索引名
2. drop index 索引名 on 表名