数值类型
- bit [(m)]--1--对应Java的boolean
- tinyint--1字节--byte
- smalint--2--short
- int--4--int
- bigint--8--long
- m指定长度,d指定小数位数
- float(m,d)--4--float
- double(m,d)--8--double
- decimal(m,d)--m/d最大值加二--decimal(能精准表示小数)
- varchar--0~65535--string
- datetime--8--1000~9999(不进行检索)
- timestamp--4--1970~2038(进行)
对库操作
- 普通数据库: create database 库名;
- 指定字符集库: create database 库名 charset utf8;
- 查重数据库: create database if not exists 库名;
- 展示数据库: show databases;
- 展示警告:show warnings;
- 使用数据库:use 库名;
- 删库: drop database 库名;
对表操作
对表操作要先使用一个数据库(use 库名;)
- 创建表:create table 表名(列名 类型,列名 varchar(20)....);
- 查看所有的表:show tables;
- 查看指定表的结构:desc 表名;
- 删除表: drop table 表名;
- -- 注释
- comment 注释
表的增删改查
- 新增:insert into 表名 values (数据,数据),(数据,数据);
- 指定列新增:insert into 表名(列名) values (数据),(数据);
- 查询表的全部内容:select * from 表名;
- 查询指定列的内容:select 列名,列名 from 表 名;
- 在查询的时候进行计算:select name, english+10 from students;(计算后拿到的是临时表,原来表中的数据不会发生改变)
- 查询时起别名:select name, english+10 as total from students;(as可以省略)
- 查询时去重:select distinct 列名 from 表名;
- 查询时排序:select * from 表名order by 列名 desc,列名asc;(不加desc默认为升序asc,俩个的花看前一个数据如果相同在看后一个)
- 条件查询:select* from 表名 where 条件;后面可以加orderby排序
- where name in(.....) like'孙%'
- 分页查询:limit 显示总行数,不足的话有多少显示多少,作用在结尾处where和orderby后
- offset :offset后面表示起始行的位置,limit 5 offset 5;
- 修改 update :update 表名 set 列的修改,列的修改 where 条件;(不加条件全部修改)
- 删除 delete :delect from 表名 where 条件;
数据库约束
- not null:这一列不能为空
- unique:这一列不能出现重复数据
- primary key:相当于前两个同时使用一个表只能有一个主键id int primary key auto_increament...........这是一个自增主键,可以在插入的时候不写这一列
- default:设置默认值 default '无名氏';
- foreign key:子表中被约束的列必须要存在于父表之中,不过如果父表不能删除子表中使用的数据foreign key (子表中被约束的列名) references父表(的主键,unique列)
表的设计
- 一对一:一个学生一个账号,一个账号一个学生
- 一对多:一个学生一个班级,一个班级多个学生
- 多对多:一个学生选多门课,一门课被多个学生选择
- 没关系
表的增删改查(进阶)
新增
将查询到的数据插入到一个新的表格中,列数和其数据类型要相同(不能多也不能少)
insert into 表名 select *from 表名;
聚合查询(行与行之间 的查询)
聚合函数中的括号与函数名要紧密贴合在一起
- count()计算行数
select count(*) from 表名 会把全null行算进去
select count(列名) from 表名 不会算null;
- sum() 列中不是数据没有意义 会先转换成double在进行计算如果失败会跳过记录一个warning
select sum(列名) from 表名
- avg()平均值
- max() min() 最大最小
分组查询(group by)
select中指定的列必须要和groupby指定的列,查询其他是没有意义
- 分组之前的条件使用where
- 分组之后的条件使用having
select role,avg(salary) from emp where name !='张三' group by role having avg(salary)
联合查询(多表查询)
内连接
分为四个步骤
- 先把两个表进行笛卡尔积
- select * from student , score;
- 指定连接条件筛选有意义的数据
- select * from student score where student.id = score.student_id;
- 根据需求进一步添加条件,此处按照名字来筛选
- select * from student, score where student.id= score.student_id and students .name='许仙;
- 针对查询结构进行精简
- select student.name, score.score from student,score where student.id= score.student_id and students .name='许仙;
也可以使用join on来代替 ,用join代替,来分割 用on来代替where
外连接
- left join 左外连接 ,左边的表存在就存在,
- right join 右外连接,右边存在就存在
- outer join全外连接 不过mysql 不支持
自连接
自己和自己进行笛卡尔积,把行问题转换成列问题
子查询
select name from student where classes_id = (select classes_id from student where name ='不想毕业');
合并查询
union自动去重/union all(全部数据)
select *from student union all select*from student2;