开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第N天,点击查看活动详情
一、数据类型
1、字符串类型
1、 char(n) : 最大是能存储255个字符;n表示字符长度
2、varchar(n) :最大是能存储65535个字符
3、enum :在指定的数据中选择一个数据(单选)
4、set :在指定的数据中选择一个或者多个(多选)
2、数值类型
1、int(n) : 存储整数范围在+-21亿以内的11位整数
2、float(m , d) : 单精度浮点型,留存小数点后6-7位(m:表示数据的总长度; d:表示小数位数)
3、double(m , d) : 双精度浮点型,留存小数点后15位(m:表示数据的总长度; d:表示小数位数)
# 浮点型会存在精度丢失问题
3、时间类型
1、year:年
2、date:年月日("年-月-日")
3、time:时分秒("时:分:秒")
4、datetime:年月日时分秒("年-月-日 时:分:秒")
写入时间是必须使用引号包裹
二、表操作
1、 表的创建
create table 表名(
字段名 数据类型,
字段名 数据类型,
字段名 数据类型
);
-- 写到最后一个字段的时候 , 不需要加逗号
-- 字段名相当于列名
-- 创建表的代码只运行一次 , 重复运行报错:表已经存在 1050 - Table 't1' already exists
-- 创建数据表
-- create table t1(name char(5));
create table t2(
name char(10),
sex enum('男','女'),
age int(3),
birthday datetime,
height double(3 , 2)
);
2、表数据插入
-- 添加一条完整的数据
insert into 表名 values(数值 , ……);
-- 添加多条完整的数据
insert into 表名 values
(数值 , ……),
(数值 , ……),
……
(数值 , ……),
(数值 , ……);
-- 添加指定字段的数据
insert into 表名(字段名,……) values(数值 , ……);
-- 添加多条指定字段的数据
insert into 表名(字段名,……) values
(数值 , ……),
(数值 , ……),
……
(数值 , ……),
(数值 , ……);
insert into t2 values
('阿宸' , '男' , 24 , '2003-7-11 12:30:30 ' , 1.79);
insert into t2 values
('梁山伯' , '男' , 19 , '2005-6-18 5:15:25' , 1.75),
('残键' , '男' , 23 , '1999-9-18 5:15:25' , 1.78),
('刘朝媛' , '女' , 19 , '1998-2-2 3:33:33' , 1.78),
('吕文浩' , '男' , 18 , '1999-9-18 5:15:25' , 1.78),
('胡桃' , '女' , 19 , '2003-7-15 7:15:15' , 1.75);
insert into t2(name , sex , age , height) values
('欧皓辰' , '男' , 24 , 1.85),
('陈冠希' , '男' , 31 , 1.81);
3、表字段的操作
1、 字段的增加
-- 默认在表末尾增加
alter table 表名 add 字段名 数据类型;
-- 添加在第一个字段
alter table 表名 add 字段名 数据类型 first;
-- 添加到某一个字段之后
alter table 表名 add 字段名 数据类型 after 字段名(被指定);
alter table t1 add age int(3);
alter table t1 add id int(5) first;
alter table t1 add class int(10) after name;
2、字段长度/数据类型的修改
alter table 表名 modify column 字段名 数据类型(长度);
注意:修改长度不能小于原有的长度 , 否则原有的数据就会被破坏,不可修复。
3、 查看表结构
desc 表名
-- 查看出表中的字段类型 , 以及长度 , 以及约束
4、字段名的修改
alter table 表名 change 旧的字段名 新的字段名 数据类型;
5、删除字段
alter table 表名 drop column 字段名;
6、清空表数据
delete from 表名;
7、修改表名
alter table 表名 rename 新的表名;
8、删除表
drop table 表名;
4、表数据查询
-- 查询表中所有字段的所有数据
select * from 表名;
-- 查询指定字段的数据
select 字段名,…… from 表名;
-- 查询数据
select * from t2;
select name , age from t2;
5、where 子句
通过筛选得到我们想要的数据
比较符号
= 等于
!=
>
<
>=
<=
逻辑运算
and
or
not
(数字要从小到大)
between 在两个值之间
not between
in 在指定集合之间
not in
where子句可以写在查询 , 修改 , 删除语句后面进行条件判断
-- 查询数据
select * from t2 where 条件;
select name , age from t2 where 条件;
-- 查询数据
-- select * from t2;
--
select name , age from t2;
-- 查询age小于20的
select * from t2 where age<20;
-- 查询age在15跟20之间的
select * from t2 where age between 15 and 20;
-- 查询age在(15 , 18 , 20 , 24)
select * from t2 where age in(15,18,20,24);
select * from t2 where age not in(15,18,20,24);
6、聚合函数
-- 求平均值
avg(字段名)
-- 求最大值
max(字段名)
-- 求最小值
min(字段名)
-- 求和
sum(字段名)
-- 统计一个字段的数据条数(长度)
count(字段名)
-- 求age的平均值
select avg(age) from t2;
-- 获得age最大的同学的所有信息
select name , max(age) from t2;
-- 统计name有多少条数据
select count(name) from t2;
-- 统计birthday有多少条数据
select count(birthday) from t2;