自增序列:auto_increment
会有一个值自动递增,一般用于id自增
注意:
1.自增:不可以逆转,就算删除表中的数据,自增序列还会存在,除非你删除表,序列才会消失
2.末尾不加auto_increment=100的情况下,默认从1开始,如果加上,就从100开始
语法:create 表名(字段名 数据类型 primary key auto_increment)可选参数 auto_increment=100;
drop table if exists t1;
create table t1(
id int primary key auto_increment comment '序号',
name char(50)
)auto_increment = 100;
desc t1;
insert into t1(name) values("Andy");
DQL(data query language)数据库查询语言
关键字:select
查询方式:全量查询、条件查询、关键字查询、内置函数查询、关联查询
-- 全量查询 * 表示所有
select * from emp;
-- 条件查询 where 条件
-- 查询 底薪大于1500的员工
select * from emp where sal > 1500;
关键字查询
排序:order by 字段
注意:
1.默认是升序,如果要降序就在语句后面加上一个desc
2.order by 关键字一定要放在sql语句的最后
-- 根据sal排序查询
select * from emp order by sal desc;
-- 根据20号部门的sal来排序
select * from emp where deptno = 20 order by sal asc; -- asc表示升序 默认就是asc 所以可以不写
select * from emp where deptno = 20 order by sal desc;
去重关键字 distinct
注意:
distinct 只能在select子句中使用一次
distinct 只能写在select子句的第一个字段前面,如果有多个字段,则会失效
用法:
一般用于子查询中,给外层查询提供查询条件
-- 根据job去重查询
select distinct job from emp; -- 正确
select ename,distinct job from emp; -- 语法错误
select distinct job,ename from emp; -- 逻辑有问题
模糊查询
关键字:like
作用:用于搜索匹配字段中的指定内容
通配符:
主要是用来配合like使用的
% 可以代表任意长度的字符,长度可以是0 比如:a%b可以代表accccb ab acb
_ 只能代表单个字符,长度不可以是0 比如 a_b 可以代表 acb aab 不能ab accccb
什么时候用?就是你不知道具体真正的字符,或者懒得输入的时候,就可以用通配符来取代具体的字符
-- 查询名字以s开头的员工的信息
select * from emp where ename like "smith";
select * from emp where ename like "s%";
-- 查询员工名字中包含E的员工有哪些?
select * from emp where ename like "%e%"; -- eaaa aaae aaeaa这些都可以满足
-- 查询名字中第3个字母是N的员工的信息?
select * from emp where ename like "__n%";
-- 默认情况下like是忽略大小写的,如果你非要区分大小写
select * from emp where ename like binary '__n%'; -- 查不出来
select * from emp where ename like binary '__N%'; -- 可以查出来
-- 查询名字中第3个字母不是是N的员工的信息?
select * from emp where ename not like "__n%";
select * from emp where ename = "smith";
select * from emp where ename like "smith";
范围查询:
关键字:in 用于查询某一个范围内的数据
-- 查询部门是20,30号的员工信息
select * from emp where deptno = 20 or deptno = 30;
select * from emp where deptno in (20,30);
区间查询
关键字:between and
注意: and左边的值一定要<and右边的值
-- 查询基本工资在1250 到 1600之间的员工信息
select * from emp where sal between 1250 and 1600; -- 正确
select * from emp where sal between 1250 and 1250; -- 这个是对的,但是没有意义
select * from emp where sal between 1600 and 1250; -- 不会报错,但是逻辑不对,查询不出来结果
分页查询
关键字 limit m,n
m: 表示从哪一行开始查
n: 表示查询多少条
分页的计算公式:
m = (当前页-1)*每页显示的条数
举例:我有11条数据,每页要显示5条,一共3页(1:5 2:5 3:1) 1 2 3 4 5 6 10 20 50
第一页 m = (1-1)*5 m=0
第二页 m = (2-1)*5 m=5
第二页 m = (3-1)*5 m=10
-- 查询员工表前5条数据
select * from emp limit 0,5;
select * from emp limit 5,5;
select * from emp limit 10,5;
-- 获取薪水大于1250的其中的1条数据
select * from emp where sal > 1250 limit 1;