MySQL表数据查询
-- 数据类型
/*
1、字符类型
char(n)
varchar(n)
enum() 单选
set() 多选
2、数值类型
int(n)
float(m ,d) m:数据的总长度 , d:小数位数
double(m , d)
3、时间类型(写入时间必须使用引号包裹)
year
date
time
datetime
*/
-- 表操作
/*
表的创建
create table 表名(
字段名 数据类型,
字段名 数据类型,
字段名 数据类型
);
*/
-- 数据插入
insert into 表名 values(数值……);
insert into 表名(字段名……) values
(数值……),
(数值……),
(数值……),
(数值……);
-- 表字段的操作
-- 字段的增加
alter table 表名 add 字段名 数据类型;
alter table 表名 add 字段名 数据类型 first;
alter table 表名 add 字段名 数据类型 after 字段名(被指定);
-- 字段数据类型/长度的修改
alter table 表名 modify column 字段名 数据类型(长度);
-- 查看表结构
desc 表名;
-- 字段名的修改
alter table 表名 change 旧的字段名 新的字段名 数据类型;
-- 删除字段
alter table 表名 drop column 字段名;
-- 清空数据
delete from 表名;
-- 修改表名
alter table 表名 rename 新的表名;
-- 删除表
drop table 表名;
-- 数据查询
select * from 表名;
select 字段名…… from 表名;
/*
where子句
数据筛选
通常结合查询 , 修改 , 删除的语句之后一起使用
比较符号
逻辑运算
(数字一定要从小到大)
between
not between
in
not in
*/
select * from 表名 where 条件;
select 字段名…… from 表名 where 条件;
-- 聚合函数
avg()
max()
min()
sum()
count()
一、约束条件
对表中的数据进行限定 , 保证数据的正确性 , 有效性 ,完整性。
约束条件在创建表的时候 , 写在数据类型后面
1、not null:非空约束,表示该字段不能为空 ,插入数据时必须传入数值
create table t2(
id int(2),
-- 该字段不允许不传值
name char(5) not null
);
desc t2;
insert into t2 values(1024 , '阿宸');
2、default :设置默认值 , 在这个字段中如果没有数据的传入 , 会将默认值进行填充
create table t3(
name char(3),
-- 选项的默认值必须是选项里面有的
sex enum('男','女') default '男'
);
insert into t3 values('张三' , '女');
insert into t3(name) values('李四');
3、unique :唯一约束,字段值唯一不能重复
create table t4(
id int unique,
name char(4)
);
insert into t4 values
(1001 , '武则天'),
(1002 , '孙悟空'),
(1003 , '鲁班'),
(1004 , '孙尚香'),
(1005 , '雅典');
insert into t4 values(1006 , '王昭君');
4、primary key : 主键约束 , 确保数据唯一且不能为空
create table t5(
id_card int primary key
);
insert into t5 values('440572');
insert into t5 values('440573');
5、auto_increment :自动增加(要把对应的字段设置为主键) , 会默认设置一个int类型 , 默认是从1或者从上一条数据的数值开始往后递增1.
create table t6(
id int primary key auto_increment,
name char(5)
);
insert into t6(name) values('小燕');
insert into t6 values(5 , '曦宇');
insert into t6(name) values('南枝');
二、数据更新
1、 表数据修改
update 表名 set 字段名= 值,…… where 条件;
-- 如果修改没有where子句的话 , 就整个字段中的所有数据全部修改
2、表数据删除
delete from 表名 where 条件;
# 如果没有where子句就会将整个表数据进行清空
三、数据查询进阶
1、模糊查询
like子句:在where子句中, 可以使用该子句以及关键字结合实现模糊查询
select * from 表名 where 字段名 like '关键字';
通配符
% : 表示匹配0个或者多个字符(NULL除外)
_ : 表示匹配任意一个字符(多个_ , 就匹配对应个数)
可以在通配符前后指定文字
select * from t7 where name like '刘%';
select * from t7 where name like '_宸';
select * from t7 where name like '%皓%';
2、消除重复项
对查询的结果去重 —— distinct
select distinct * from 表名;
select distinct height,name from t7;
select distinct sex from t7;
select distinct age from t7;
select distinct * from t7;
3、排序
在查询中添加拍寻 ,
select * from 表名 order by 字段名 desc;
默认为升序
asc :按照指定的字段升序排序(默认)
desc:降序排序
select * from t7 order by age;
select * from t7 order by age desc;
select * from t7 where age>20 order by height;
select * from t7 order by height desc;