文章目录

  • part I 操作语句
    • 一、数据库操作(DDL)
      • 1) 建立数据库
      • 2) 查看数据库
      • 3) 使用数据库
      • 4) 删除数据库
    • 二、表操作(DDL)
      • 1) 建表语法
      • 2) 临时表
      • 3) 建相同结构空表
      • 4) 通过获得原表建表语句复制/修改来建表(克隆)
      • 5) 复制表
      • 6) 修改表名
      • 7) 删除表
      • 8) 展示所有表
    • 三、表字段操作(DDL)
      • 1) 增加表字段
      • 2) 修改表字段名
      • 3) 修改表字段类型
      • 4) 修改表字段约束
      • 5) 查看表字段结构
      • 6) 删除表字段
    • 四、表数据操作(DML)
      • 1) 插入表数据
      • 2) 抽取复制表数据
      • 3) 更新表数据(省略where将对所有数据更新)
      • 4) 删除表数据(省略where将对所有数据删除)
      • 5) 清空表数据
      • 6) 查询表数据
  • part II 查询语句(DQL)
    • 1) 简单查询
      • 1.查询所有字段数据
      • 2.查询指定字段数据
      • 3. 查询去重后的某个字段数据
      • 4.计算某字段数据内容种类个数
      • 5.添加条件后显示
    • 2) 条件查询
      • 1.条件选择where 字符
      • 2.条件选择where 数值
      • 3.查看NULL空值(区别于0和空白)
      • 4.条件选择where like
      • 5.多重条件选择 where and
      • 6.多重条件选择where not
      • 7.多重条件选择where or
      • 8.多重条件选择where not and or
      • 9.多重条件查询 where in(同字段条件or的简写)
      • 10.多重条件查询之范围 where between(适用于数字、文本、日期)
      • 11.多条件查询 where in between
    • 3) 排序查询
      • 1.排序order by
      • 2.多重排序(后一个排序是在前一个排序完毕的基础上)
      • 4.限制查询数量 top limit rownum
    • 4) group by语句
    • 5) having对分组之后的结果再进行过滤
    • 6) 连接
      • 1.内部连接 inner join (join) 两表的交集
      • 2.左连接left join 左表完整
      • 3.右连接right join 右表完整
      • 4. 全连接 都完整 full join
      • 5. 联合数据union 只显示不重复项/union all 重复项也会展示
      • 6. 自连接
      • 7. 笛卡尔连接(没有join的连接)会把所有的组合列出来
      • 8.子查询
  • part III 事务(DCL)、索引、视图
    • 1.事务
    • 2.索引
    • 3.视图
  • part IV 函数
    • 1.时间函数
      • 1) 当前日期时间:sysdate(),now(),curdate(),curtime()
      • 2) 提取日期时间或序列:date(),time(expr),extract() 等
      • 3) 日期时间增减 :date_add()|adddate(),date_sub()|subdate(),addtime(),subtime()
      • 4) 日期时间间隔:datediff(),timediff()
      • 5) 日期-字符转换格式:date_format(),str_to_date()
      • 6) 时间戳转化from_unixtime()
      • 7) 月末last_day()和月初
      • 8) 其它时间日期函数
    • 2.聚合运算函数
      • 1) max()
      • 2) min()
      • 3) count()
      • 4) avg()
      • 5) sum()
      • 6) first()
      • 7) last()
      • 8) field()返回str在str1,str2,STR3,...列表中的索引(从1开始的位置)
      • 9) sqrt开平方函数
      • 10) mod 求余数
    • 3.字符串函数
      • 1) lower() lcase()字母转换成小写
      • 2) upper() ucase()字母转换成小写
      • 3) mid()&substr()提取函数,用于从文本字段中提取字符。
      • 4) len()返回文本字段中值的长度。
      • 5) concat()函数连接字符串
    • 4.数据类型转换函数
      • 1) CAST()
      • 2) CONVERT()
    • 5.通用函数
      • 1)IFNULL()和COALESCE()
    • 6.窗口函数
      • 1).排序专用函数
        • 1) row_number()
        • 2) rank()
        • 3) dense_rank()
      • 2)聚合函数类
      • 3).取值函数

part I 操作语句

一、数据库操作(DDL)

命令窗口使用数据库

D:\MySQL\MySQL Server 8.0\bin>mysql -u root -p
Enter password: ******

1) 建立数据库

create database school;
create database if not exit school;
create database school character set 字符集;

2) 查看数据库

show databases;#查看所有数据库
select database();#查看正在使用的数据库

3) 使用数据库

use school;

4) 删除数据库

drop database school;

二、表操作(DDL)

1) 建表语法

CREATE TABLE trainee2 (s_id VARCHAR(20),s_name VARCHAR(20) NOT NULL DEFAULT '',s_birth DATE NOT NULL,#非空约束s_sex VARCHAR(10) NOT NULL DEFAULT '',OrderDate date DEFAULT GETDATE(),PRIMARY KEY (s_id),unique (s_name)constraint un_que unique (s_name,s_id),#多个列的unique约束#check (s_birthday>'1900-01-01')#mysql中check约束无效#constraint un_che check (s_birthday>'1900-01-01',s_id>0)#多个限定值约束
);
CREATE TABLE `person2` (`id` int not null auto_increment,#可以修改自增起始值alter table person auto_increment=100;`name` VARCHAR(20) NOT NULL DEFAULT '', `s_datetime` datetime default  now() ,constraint un_info PRIMARY KEY (id,name)#多个字段组成主键-联合主键
);
CREATE TABLE `course2` (`c_id` varchar(20) PRIMARY KEY,#主键约束`c_name` varchar(20) unique,#唯一约束`t_id` varchar(20) NOT NULL DEFAULT '',#默认值--外键约束foreign key (t_id) references teacher(t_id),#course表的外键指向teacher表的主键, 虽然没有给外键约束命名,但是系统也会自动命名,可通过show create table查看constraint un_fore foreign key(t_id/*,t_id2*/) references teacher(t_id) #命名 FOREIGN KEY 约束,并定义多个列的 FOREIGN KEY 约束
) ;
CREATE TABLE `mytable` (ID INT NOT NULL,username VARCHA(16),INDEX username_index(username),#创建普通索引UNIQUE id_index(ID)#创建唯一性索引
);
  1. 数据类型参考:https://www.w3cschool.cn/sql/anioefpk.html

  2. 约束类型

  • not null约束:如果不向字段添加值,就无法插入新记录或者更新记录。
  • default约束:用于向列中插入默认值。
  • 主键约束:primary key (字段名)
  • 外键约束:用于预防破坏表之间连接的行为,防止非法数据插入外键列
  • unique约束:为列或列集合提供唯一性保证(注意:PRIMARY KEY 约束拥有自动定义的 UNIQUE 约束。每个表可以有多个UNIQUE 约束,但是每个表只能有一个 PRIMARY KEY 约束。没有设主键字段时,该unique字段自动成为主键字段
  • check约束:用于限制列中的值的范围。mysql中check约束无效

constraint关键字用于联合多个字段进行约束

  1. 序列自增
    建表的时候指定主键字段自增(默认起始值是1)auto_increment,新增数据的时候就不需要为该序列赋值
    如果需要修改自增起始值
alter table person auto_increment=100;

案例:删除数据后整理自增字段

create table auto_test (id int not null auto_increment,primary key(id),name varchar(30) not null);insert into auto_test (name) values('张三'),('李四'),('王五');select * from   auto_test;SET SQL_SAFE_UPDATES = 0; /*修改数据库模式以便非主键修改*/delete from  auto_test where name='李四';/*删除后的序号是不连续的*/alter table auto_test drop id;/*需要先删除序列字段,再重新添加*/alter table auto_test add id int not null auto_increment first, add primary key (id);

2) 临时表

create temporary table temp(product_name varchar(45) not null,total_sales decimal(6,2) not null default 0.00,/*decimal(6,2)全长6位,有2位是小数*/avg_unit_price decimal(4,2) not null default 0.00,total_unit_sold int unsigned not null default 0
);
insert into temp values('computer',1205.22,22.58,4800);
select * from temp;

临时表不会在show tables命令下展示,退出mysql后也无法select该表,如果要在会话没有退出的时候删除,drop table 即可

3) 建相同结构空表

create table newt like student;

4) 通过获得原表建表语句复制/修改来建表(克隆)

show create table trainee2;#可以查看建表语句

5) 复制表

create table new2 select * from student;
create table new3 select * from student where s_sex='男';
create table new4 select s_name,s_sex from student;

6) 修改表名

alter table trainee rename learner;

7) 删除表

drop table learner;

8) 展示所有表

show tables;/*临时表将无法展示*/

三、表字段操作(DDL)

1) 增加表字段

alter table student add city varchar(45) NOT NULL;
alter table new4 add id varchar(45) NOT NULL;
alter table person add s_datetime datetime NOT NULL default now() ;
alter table person add s_datetime datetime NOT NULL default current_timestamp();
alter table person add s_datetime timestamp NOT NULL default now();
alter table person add s_datetime timestamp NOT NULL default current_timestamp();

2) 修改表字段名

alter table student change city s_city varchar(45) NOT NULL;

3) 修改表字段类型

参考数据类型手册 https://www.w3cschool.cn/sql/anioefpk.html

alter table student change s_city s_city varchar(20) NOT NULL;
alter table student modify s_city varchar(20) NOT NULL;

4) 修改表字段约束

1. not null约束是跟着字段类型走的,见上

2. 修改表主键字段自增起始值
注意:修改后插入的数据将从新的起始值开始自增,并不改变之前的数据

alter table person auto_increment=1000;

3. 添加表字段default约束
注意:只对之后添加的数据作约束,不改变之前的数据

alter table person alter name set default  'lily';

4. 删除表字段default约束

alter table person alter name drop default;

5. 添加表字段主键约束
唯一非空

alter table person add primary key (id);
alter table person add constraint un_info primary key (id,name);#联合字段主键约束

6. 删除表字段主键约束

alter table person drop primary key;

7. 添加表字段外键约束

#alter table 从表 add [constraint 外键名] foreign key (从表外键字段) references 主表(主表的主键);
alter table course2 add foreign key (t_id) references teacher(t_id);
alter table course add  constraint un_fore foreign key (t_id/*,t_id1*/) references teacher(t_id);

主表和从表的关系是一对多,有了外键约束,从表添加数据会受到主表限制,主表删除数据会受到从表限制
8. 删除外键约束

#alter table 从表 drop foreign key 外键名称;
alter table course2 drop foreign key un_fore;
#注意这里un_fore是自己重命名的约束名称,如果是用未另命名方式创建的外键约束,应该先show create table 查看建表语句,系统会自动给出外键约束的重命名,找到该外键约束名

9. 添加unique约束
唯一约束

alter table trainee2 add unique (s_name);
alter table trainee2 add constraint un_que unique (s_id,s_name);

注意:NULL和NULL不相等,不受唯一约束限制
10. 删除unique约束

alter table trainee2 drop index s_name;

11. 添加check约束 :mysql中check约束无效

alter table trainee2 add check (s_birthday>'1900-01-01') ;
alter table trainee2 add constraint un_che check (s_birthday>'1900-01-01' and s_id>0) ;

12. 删除check约束:mysql中check约束无效

alter table trainee2 drop check un_che;

5) 查看表字段结构

desc student;

6) 删除表字段

alter table student drop s_time;
alter table person drop s_datetime;

四、表数据操作(DML)

1) 插入表数据

insert into student values('09' , '黄渤' , '1990-01-01' , '男');
insert into student values('10' , '闫妮' , '1990-02-01' , '女'),('11' , '孙杨' , '1990-01-01' , '男');#插入多条数据
insert into person (name) values('jahh');#自增字段不需要赋值 s_time自动在插入时记录

2) 抽取复制表数据

insert into newt select * from student;#表结构相同,数据全部复制 但是会有主键冲突
insert into newt select * from student where s_sex='男';#有条件地复制
insert into new4 (id) select s_id from student where s_sex='男';#id是后来add的,这种方式只会在表后面单纯追加
insert into newt (s_id,s_birth,s_city,s_ename )select s_id,s_birth,s_city,s_ename from student where s_sex='男';#复制部分字段
insert into student select * from newt where s_id in (select s_id from person2 where s_birthday>'2018-01-01');#子查询之用于insert语句 主键冲突
insert into student select * from newt where s_birthday>'2018-01-01';#子查询之用于insert语句 相同效果 主键冲突

3) 更新表数据(省略where将对所有数据更新)

update student set s_name='黄磊' where s_id='09';
update student set s_id='099',s_name='黄磊' where s_id='09';#更新多个字段
update student set s_name='男生' where s_sex='男';#更新多个数据
update employee set salary = salary + 1000 where name ='小红';#变量赋值
update newt set s_name='男生' where s_sex in (select s_sex from newt where s_sex='男');#子查询之用于update语句
select s_sex from newt where s_sex='男';

4) 删除表数据(省略where将对所有数据删除)

delete from student where s_id='09';
delete from newt where newt.s_birthday in (select s_birthday from newt where s_birthday>'2016-01-01');#mysql 会出现以下报错
  1. 在使用mysql执行update的时候,如果不是用主键当where语句,会报如下错误“you are using safe update”,使用主键用于where语句中正常。
    解决方案是修改数据库模式:
 SET SQL_SAFE_UPDATES = 0;
  1. 不能先select出同一表中的某些值,再update这个表(在同一语句中),即不能依据某字段值做判断再来更新某字段的值。
    注意:如果有自增字段,被删除某条记录后,原来的id不变,并不会自动补齐(例如序数3被删了之后再添加就会从4开始,而不是3,原来的3仍旧被占用,即使将表里的数据全部删除,新添加的第一条仍旧会延用之前的序列)

5) 清空表数据

truncate table newt;

truncate删除整个表,再重建新表
清空表数据后,用自增方式建立的序列将会不与之前的数据连续,自增重新从1开始

6) 查询表数据

见 part II

part II 查询语句(DQL)

1) 简单查询

1.查询所有字段数据

select * from student;#查询所有数据

2.查询指定字段数据

select s_name,s_sex from student;#查询指定列所有数据
select s_name as stuname ,s_sex as 'stu sex'  from student as stu;# as 定义别名
select concat(s_name,'#',s_sex,'#',s_birthday)as 'basic info'  from student;#concat 连接字符串

3. 查询去重后的某个字段数据

select distinct s_sex from student;
select distinct s_name,s_sex from student;#两个字段都重复了去重

4.计算某字段数据内容种类个数

select count(distinct s_sex) from student;

5.添加条件后显示

select price+10 from product;#使用表达式

2) 条件查询

  • like 通配符:
    可参考
    https://blog.csdn.net/qq_34359327/article/details/78601426
    https://blog.csdn.net/win7system/article/details/53508401

1.条件选择where 字符

select * from student where s_sex='女';

2.条件选择where 数值

select * from score where s_score>80;

3.查看NULL空值(区别于0和空白)

#alter table student modify s_birthday DATE;  #先修改字段类型使该字段可以值为空
#insert into student (s_id,s_name,s_sex) values ('09','陈与','男'); #插入不完整的一条记录
select * from student where s_birthday is not null;
/*不能使用=NULL和<>NULL 只能使用is NULL和 is not NULL*/
#delete from student where s_id='09'; #删除该条数据

4.条件选择where like

select * from student where s_birthday like '1990%';
select * from student where s_birthday like '__8%';
select * from student where s_name  regexp '[梅兰竹菊]$';#姓名以[]中字符结尾的数据
select * from student where s_name not rlike '^[赵李]';#姓名不以[]中字符开头的数据

5.多重条件选择 where and

select * from student where s_birthday like '1990%' and s_sex='男';

6.多重条件选择where not

select * from student where not s_sex='男';

7.多重条件选择where or

select * from student where s_sex='男' or s_name like '%王%';

8.多重条件选择where not and or

select * from student where s_sex='女' and (s_birthday like '1990%' or s_birthday like '1991%');
select * from student where s_sex='女' and s_birthday like '1990%' or s_birthday like '1991%';

优先级:not>and>or,使用括号可以改变优先级

select * from student where not s_sex='女' and not s_birthday like '1991%';
select * from student where not s_sex='女' and s_birthday like '1990%';
select * from student where not s_sex='女' or s_birthday like '1989%';

9.多重条件查询 where in(同字段条件or的简写)

select * from student where s_id='01' or s_id='03';
select * from student where s_id in ('01','03');
select * from student where s_id not in ('01','03');
select c_name from course where c_id in (select c_id from score where s_id='05');

10.多重条件查询之范围 where between(适用于数字、文本、日期)

select * from student where s_birthday between '1990-01-01' and '1990-12-31';
select * from student where s_birthday  NOT between '1990-01-01' and '1990-12-31';
select * from student where s_ename between 'a%' and 'm%';#这里的关系是[ )

11.多条件查询 where in between

select * from student where (s_ename between 'a%' and 'm%') and s_sex='女';#最好加()

3) 排序查询

1.排序order by

select * from score order by c_id asc;#asc不写也默认升序排列

2.多重排序(后一个排序是在前一个排序完毕的基础上)

select * from score order by c_id asc,s_score desc;

后一个条件只有当第一个字段同序时才起作用

4.限制查询数量 top limit rownum

select  * top 3 from student; #mysql不支持top语法  SQL Server / MS Access支持
select * from score limit 3;#Oracle 语法不支持
select * from score order by s_score desc limit 3 ;
# select * from 表 limit 起始位置(从0开始计),条数;--分页显示(从指定位置显示指定条数)
select * from student where ROWNUM<=3;#mysql不支持top语法  Oracle 语法支持

补充:limit offset,可结合orderby 使用

selete * from testtable limit 2,1;
--跳过2条取后面的1条
selete * from testtable limit 2 offset 1;
--跳过1条取后面的2条

4) group by语句

select * from score where c_id=03 group by s_id;
select * from score group by s_id;/**实际上没有筛选的分组,每组只显示组内第一个数据,所以group by一般结合聚合运算函数使用*/
select s_id,avg(s_score) from score group by s_id;/*按照学号分组,得到每个学生的平均分 */
select c_id,avg(s_score) from score group by c_id;/*按照学科分组,得到每门学科的平均分 */

分组后的语句,select的后面只能跟分组关键字和聚合函数

延生:组内汇总聚合;with rollup

SELECTCOALESCE(j.分公司,'ZB') as 渠道,COALESCE(j.门店,j.分公司) as 渠道标识,SUM(j.交易额) AS amount
FROMjye j
GROUP BYj.分公司,j.门店 WITH ROLLUP-- oracle中 GROUP BY ROLLUP(j.分公司,j.门店)

5) having对分组之后的结果再进行过滤

-- where关键字无法与运算函数一起使用
select * from score where c_id='02' group by s_id ;
select * from score  group by s_id having c_id=02;#每组只显示组内第一个数据,在此基础上having再做的筛选
select * from score where c_id='01' group by s_id having s_score>60;
select * from score where s_score>60 group by s_id having c_id='01';
select s_id,avg(s_score) as avge from score group by s_id having avge>60;
/****查询每人最高及格成绩及对应的科目******/
select maxscore.*,score.c_id from (select score.s_id,max(score.s_score) as max_score from score group by score.s_id) as maxscore inner join score on maxscore.max_score=score.s_score where maxscore.s_id=score.s_idhaving maxscore.max_score>60;

sql语句的执行顺序:
from>where>group by>聚合函数>having>select>order by>limit

6) 连接

insert into course values ('04','化学','05');
insert into teacher values ('04','方圆');#另外插入一条teacher数据用于对比

1.内部连接 inner join (join) 两表的交集

##同义语句:from A join B on cindition == from A,B where condition
select course.c_id,course.c_name,teacher.t_name from course inner join teacher on course.t_id=teacher.t_id order by course.c_id desc;
select course.c_id,course.c_name,teacher.t_name from course,teacher where course.t_id=teacher.t_id order by course.c_id desc;
/****查询每人最高成绩及对应的科目******/
select score.s_id,max(score.s_score) as max_score from score group by score.s_id;
select maxscore.*,score.c_id from (select score.s_id,max(score.s_score) as max_score from score group by score.s_id) as maxscore inner join score on maxscore.max_score=score.s_score where maxscore.s_id=score.s_id;    

2.左连接left join 左表完整

select course.c_id,course.c_name,teacher.t_name from course left join teacher on course.t_id=teacher.t_id;
select course.*,teacher.* from course left join teacher on course.t_id=teacher.t_id where teacher.t_name is null;#排除集

一般左表放明细表,右表放连接关键字意义上的汇总表,这样坐表的数据就不会因为连接而重复,在做聚合计算的时候就不会受到干扰

3.右连接right join 右表完整

select course.c_id,course.c_name,teacher.t_name from course right join teacher on course.t_id=teacher.t_id;

4. 全连接 都完整 full join

select course.c_id,course.c_name,teacher.t_name from course full  join teacher on course.t_id=teacher.t_id;

5. 联合数据union 只显示不重复项/union all 重复项也会展示

#mysql不支持top语法 , 使用union可实现效果

select course.c_id,course.c_name,teacher.t_name from course left join teacher on course.t_id=teacher.t_id
union #all
select course.c_id,course.c_name,teacher.t_name from course right join teacher on course.t_id=teacher.t_id;
#上下联合的两张表需要有相同的列数
/*
select * from score
union
select * from student;
报错*/

6. 自连接

alter table student add s_city varchar(20) not null;
select A.s_name as name1,B.s_name as name2 ,A.s_city from student A,student B where  A.s_id<>B.s_id and A.s_city=B.s_city;#student A 中间省略as ,用作表别名
select A.s_name as name1,B.s_name as name2 ,A.s_city from student A join student B on A.s_city=B.s_city ;
select * from score SC1 join score SC2 on SC1.s_id=SC2.s_id  where SC1.s_score>SC2.s_score and SC1.c_id=01 and (SC2.c_id=02 or SC2.c_id=NULL);
select * from score SC1 join score SC2 on SC1.s_id=SC2.s_id and (SC2.c_id=02 or SC2.c_id=null) and SC1.c_id=01 where SC1.s_score>SC2.s_score;

7. 笛卡尔连接(没有join的连接)会把所有的组合列出来

简单的两表相乘

select course.c_name,teacher.t_name from teacher,course;

8.子查询

子查询规则:

  • 子查询必须在圆括号内
  • 子查询的select子句中只能有一个列,除非主查询中有多个列,用于与子查询选中的列相比较。
  • 子查询不能有order by,子查询中group by可以起到同order by相同的作用
  • 返回多行数据的子查询只能同多值操作符一起使用,比如in 操作符
  • select列表中不能包含任何对BLOB,ARRAY,CLOB或者NCLOB类型值的引用
  • 子查询不能直接用在集合函数中
  • BETWEEN操作符不能同子查询一起使用,但是BETWEEN操作符可以用在子查询中

– 子查询之用于select语句

----将子查询当做值
-- 找到01课程及格的人员名单
select student.s_name from student where s_id in
(select score.s_id from score where score.c_id='01' and score.s_score>=60);--查询最高价格的所有产品
select *  from products
where price=(select max(price) from products);----将子查询作为临时表
--在产品表里查找化妆品类的信息(产品表里没有品类名称)
select * from products A
left join
(select * from category where cname='化妆品') B on A.categoryid=B.cid

– 子查询之用于insert语句,见【表数据操作-插入数据表】
– 子查询之用于update语句
– 子查询之用于select语句

part III 事务(DCL)、索引、视图

1.事务

– COMMIT --提交更改
– ROLLBACK [TO SAVEPOINT_NAME]–撤销至上次commit命令或者rollback执行以来的事务
– SAVEPOINT [SAVEPOINT_NAME] --标记事务中的一个状态点
– RELEASE SAVEPOINT SAVEPOINT_NAME 删除先前创建的保存点
– SET TRANSACTION[READ WRITE | READ ONLY] --初始化数据库事务,读写或者只读。

2.索引

减少查找范围,快速定位
B-数索引
哈希索引

普通索引:普通列
唯一性索引:列值时不重复的
主键索引:一个表有了主键,自动加主键索引

– 创建索引

##创建普通索引
#create index 索引名 on 表名(字段名);
create index s_id_index on student(s_id);
#alter table 表名 add 索引名(字段名);
alter table student add index s_id_index(s_id);#创建普通索引,并且可以给索引命名
##创建唯一索引
create unique index s_id_unindex on student(s_id);
alter table student add unique s_id_unindex(s_id);
##创建主键索引
alter table student add primary key(s_id_pk);#创建主键索引

也可以在创建表的时候创建索引,见上文
– 删除索引

drop index s_id_index on student;#删除普通索引\删除唯一索引
alter table student drop index s_id_index;#删除普通索引\删除唯一索引
alter table student drop primary key;#删除主键索引(只能删除主键索引)

– 查看索引

show index from student;
show keys from student;

创建和维护索引需要耗时
索引也会占用物理空间
表数据变化时,索引也会变化
对于经常增删改的表不建议添加索引,对很少发生变化的表适合建立索引,建在经常被查询访问的列上

3.视图

– 创建视图

create view view_test as
select s_name,s_birthday from student where s_sex='男';

– --WITH CHECK OPTION用于保证所有的 UPDATE 和 INSERT 语句都满足视图定义中的条件。

create view view_test as
select s_name,s_birthday from student where s_sex='男' with check option;

– 查询视图

select * from view_test;
select * from view_test where s_birthday<'1990-12-30';

– 更新视图

create or replace view view_test as
select s_name,s_city,s_birthday from student;
update view_test set s_name='zhaolei' where s_birthday='1990-01-01';#会修改到源数据

– – 向视图中插入新行#视图必须包含原始数据表中所有的 NOT NULL 列,从而使 INSERT 查询生效。
– 撤销视图(无法查询视图)

drop view view_test;

/注入***/
– 暂时忽略–

part IV 函数

1.时间函数

– 参考 https://www.cnblogs.com/caicaizi/p/7813518.html,
注意datetime也支持默认值,见表字段操作之添加表字段

1) 当前日期时间:sysdate(),now(),curdate(),curtime()

now()可以作为默认值设置

select now(),curdate(),curtime(),sysdate();
-- 2020-12-04 16:50:58  2020-12-04  16:50:58    2020-12-04 16:50:58
  • CURRENT_TIME 和 CURRENT_TIME() 是 CURTIME() 的别名。
  • CURRENT_TIMESTAMP 和 CURRENT_TIMESTAMP() 是 NOW() 的别名。
  • LOCALTIME 和 LOCALTIME() 是 NOW() 的别名。
  • LOCALTIMESTAMP 和 LOCALTIMESTAMP() 是 NOW() 的别名。

2) 提取日期时间或序列:date(),time(expr),extract() 等

  • date()提取日期,time(expr)提取时间
select date(now()),time(now());
--2020-12-04    16:53:30
  • extract() 提取更细致的时间数据
    – 可以抓取[year \quarter \month \week\ day \hour \minute \second \second_microsecond\ MINUTE_MICROSECOND \HOUR_MICROSECOND \DAY_MICROSECOND \MINUTE_SECOND \HOUR_SECOND \DAY_SECOND \HOUR_MINUTE \ DAY_MINUTE \DAY_HOUR \YEAR_MONTH]
select extract(year from now()) as lyear,extract(month from now()) as lmonth, extract(week from now()) as lweek,extract(day from now()) as lday, extract(hour from now()) as lhour,extract(minute from now()) as lminute,extract(second from now()) as lsecond,extract(second_microsecond from now()) as lsecond_microsecond,extract(YEAR_MONTH from now()) as YEAR_MONTH1
-- 2020 12  48  4   17  32  4   4000000 202012
  • 返回日期的序列
    dayofmonth()当月第几天 0-31,同day()
    year(date)返回 date 的年份部分;
    hour()返回一天中的小时数0-23;
    minute()返回时间型值的分钟部分0-59;
    month()返回月份 0-12;
    quarter()所处季度1-4;
    second()返回秒0-59;
select year(now()),quarter(now()),month(now()),week(now()),day(now()),weekday(now()), hour(now()),minute(now()),second(now());
--2020  4   12  48  4   4   17  28  10select dayofmonth(now());
--4

dayofweek()当周的第几天,1=sunday;weekday(date)返回 date 是其所在星期的第几天 (0 = Monday, 1 = Tuesday, . 6 = Sunday)。

select dayofweek(now()),WEEKDAY(now());#今日周五
-- 6 4

yearweek(date), yearweek(date,mode)返回 date 所在的年份和周数。mode 参数意义与 week() 函数的完全一样。

select YEARWEEK(now());
-- 202048 #2020年的第48周

WEEK(date[,mode])该函数将返回 date 所在的周是当年的第几周。

select WEEK(now())
-- 48
select WEEK(now(),3)
-- 49

weekofyear(date)返回 date 所在的周是当年的第几周,范围从 1 到 53.其功能同 week(date, 3)相同。

select WEEKOFYEAR(now());
-- 49

dayofyear()当年的第几天

select dayofyear(now());
-- 339 #第339天

3) 日期时间增减 :date_add()|adddate(),date_sub()|subdate(),addtime(),subtime()

  • 向日期添加指定日期时间间隔
    date_add(date,INTERVAL expr unit)
    ADDDATE(date,INTERVAL expr unit),ADDDATE(expr,days)
    第二个参数是interval形式,adddate()与date_add()相同,
    type 除了date ,还可以是上述[]中的类型
select date_add(s_birthday, interval 45 day) as laterdate from student;
select adddate(s_birthday, interval 45 day) as laterdate from student;
select date_add(s_birthday, interval '1:1' MINUTE_SECOND) as laterdate from student;
  • 向日期减去指定日期时间间隔
  • date_sub(date,INTERVAL expr unit)
  • SUBDATE(date,INTERVAL expr unit),SUBDATE(expr,days)
    当第二个参数为 INTERVAL 形式时,SUBDATE() 就是 DATE_SUB() 的别名。
select date_sub(s_birthday, interval 45 day) as foredate from student;
select date_sub(now(), interval 1 day);
  • 向指定日期时间增减时间
    addtime(expr1,expr2)返回 expr1+expr2
    结果的格式与 expr1 相同。expr1 是一个时间型(time)或者 datetime 型的表达式,expr2 是时间型值。
select now(),ADDTIME(now(),'1:1:1')
-- 2020-12-04 17:06:14  2020-12-04 18:07:15
  • 向指定日期时间减去时间
    subtime(expr1,expr2)返回 expr1-expr2,
select now(),SUBTIME(now(),'1:1:1')
-- 2020-12-04 17:04:04  2020-12-04 16:03:03

4) 日期时间间隔:datediff(),timediff()

  • datediff()返回两个日期的天数
select datediff(now(),'2018-5-11') as diffdate;
--938
  • timediff(expr1,expr2)返回 expr1-expr2,结果为时间型值。expr1 和 expr2 可以为时间型或者 datetime 型表达式,不过二者必须为相同类型。
select timediff(now(),'2018-5-11 12:25:26') as diffdate;
-- 838:59:59

5) 日期-字符转换格式:date_format(),str_to_date()

  • date_format(date,format)以不同的格式显示
    以特格式显示后便于直接参与比较运算
select date_format(now(),'%m-%d-%Y');
select date_format(now(),'%W %M %Y');
select * from  t_orders where DATE_FORMAT(create_time,'%Y%m%d') >=20190205
select * from  t_orders where DATE_FORMAT(create_time,'%Y%m%d') >='20190205'
  • str_to_date(str,format)是date_format(date,format) 函数的逆函数
select str_to_date('04-03-2019','%m-%d-%Y');

format写法:
含义参考 https://www.w3cschool.cn/mysql/func-date-format.html

格式 描述
%a 缩写星期名
%b 缩写月名
%c 月,数值
%D 带有英文前缀的月中的天
%d 月的天,数值(00-31)
%e 月的天,数值(0-31)
%f 微秒
%H 小时(00-23)
%h 小时(01-12)
%I 小时(01-12)
%i 分钟,数值(00-59)
%j 年的天(001-366)
%k 小时(0-23)
%l 小时(1-12)
%M 月名
%m 月,数值(00-12)
%p AM 或 PM
%r 时间,12-小时(hh:mm:ss AM 或 PM)
%S 秒(00-59)
%s 秒(00-59)
%T 时间, 24-小时(hh:mm:ss)
%U 周(00-53)星期日是一周的第一天
%u 周(00-53)星期一是一周的第一天
%V 周(01-53)星期日是一周的第一天,与 %X 使用
%v 周(01-53)星期一是一周的第一天,与 %x 使用
%W 星期名
%w 周的天(0=星期日, 6=星期六)
%X 年,其中的星期日是周的第一天,4 位,与 %V 使用
%x 年,其中的星期一是周的第一天,4 位,与 %v 使用
%Y 年,4 位
%y 年,2 位

6) 时间戳转化from_unixtime()

from_unixtime(unix_timestamp,format)返回UNIX时间戳对应的日期

SELECT FROM_UNIXTIME(875996580);
-- 1997-10-05 04:23:00

7) 月末last_day()和月初

last_day()返回所在月的最后一天

select last_day(now());
-- 2020-12-31

TIP:月初

select DATE_SUB(curdate(),interval day(curdate())-1 day)
--2020-12-01

8) 其它时间日期函数

  1. convert_tz转换时区
select convert_tz(s_datetime,'GMT','MET') from person;
select convert_tz(s_datetime,'+00.00','+12.00') from person;
select convert_tz(now(),'GMT','MET');
select convert_tz('2004-01-01 12:00:00','GMT','MET');/*返回NULL,原因是mysql的mysql数据库中没有对应的time_zone表*/
SELECT CONVERT_TZ(now(),'+00:00','+10:00');
  1. DAYNAME()星期名称

select dayname(now());
-- Friday
  1. monthname()所处月份全名
select monthname(now());
-- December
  1. from_days给出天数,返回date值
select from_days(735522.00);
-- 2013-10-16
select from_days(0.00);
  1. makedate()给定年份和所在当年的天数
select makedate(2019,55);
  1. maketime()给定时分秒,构造对应时间值
select maketime(13,25,58);
  1. microsecond(),返回微秒数
select microsecond('12:00:00.123456');
  1. PERIOD_ADD(P,N) 在时间 P(格式为 YYMM 或者 YYYYMM)上加上 N 个月,结果格式为 YYYYMM。注意,时间参数 P 并不是日期型值。
SELECT PERIOD_ADD(9801,2);
  1. PERIOD_DIFF(P1,P2)返回时间 P1 和 P2 之间相差的月份。
SELECT PERIOD_DIFF(9802,199703);
  1. sec_to_time()秒数转换成时分秒格式
select sec_to_time(4515);
  1. TIME_TO_SEC(time)将时间型值转换为秒。
select TIME_TO_SEC('08:12:55');
  1. TIMESTAMP(expr),TIMESTAMP(expr1,expr2)
    只有一个参数的时候,该函数由日期型或者 datetime 型表达式返回一个 datetime 型值。有两个参数的时候,该函数将 expr2 加到日期型或 datetime 型值 expr1 上,并返回 datetime 型的结果。

  2. TIMESTAMPADD(unit,interval,datetime_expr)
    将整数型的表达式 interval 加到日期型或者 datetime 型表达式 datetime_expr 上。单位由 unit 参数给出,其取值应为以下几种中的一种:FRAC_SECOND、SECOND、MINUTE、HOUR、DAY、WEEK、MONTH、QUARTER 或者 YEAR。

  3. TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
    返回日期型或者 datetime 型表达式 datetime_expr1 和 datetime_expr2 的差。结果的单位由 unit 参数给出,unit 的取值规定同 TIMESTAMPADD() 函数。

  4. TIME_FORMAT(time,format)
    该函数使用起来类似 DATE_FORMAT() 函数,但是格式字符串 format 中只能有与小时、分钟和秒有关的那些占位符。

  5. TO_DAYS(date)给定日期型值 date,返回天数(自公元 0 年以来的天数)。

  6. UNIX_TIMESTAMP(), UNIX_TIMESTAMP(date)
    不带任何参数时,该函数返回一个 unsigned integer 型的 UNIX 时间戳(自 ‘1970-01-01 00:00:00’ UTC 以来的秒数)。如果有一个参数 date 的话,该函数返回自 ‘1970-01-01 00:00:00’ UTC 至 date 的秒数。date 可以是日期型的字符串、DATETIME 型的字符串、时间戳或者 YYMMDD 或 YYYYMMDD 格式的数字。

  7. UTC_DATE, UTC_DATE()返回当前 UTC 日期,格式为 ‘YYYY-MM-DD’ 或者 YYYYMMDD

  8. UTC_TIME, UTC_TIME()返回当前 UTC 时间,格式为 ‘HH:MM:SS’ 或者 HHMMSS

2.聚合运算函数

1) max()

select max(s_score) as lagestscore from score where c_id=03;

2) min()

select min(s_score) as smallestscore from score where c_id=03;

3) count()

select count(*) as numamount from score where c_id=03;
select count(distinct s_score) from score where c_id=03;/*找出c_id=03,并且s_score不重复*/

4) avg()

select avg(s_score) as avgscore from score where c_id=03;
select * from score where s_score>(select avg(s_score) from score where c_id=03) and c_id=03 ;

5) sum()

select sum(s_score) as sumscore from score where c_id=03;

6) first()

MS Access 支持 FIRST() 函数。MySql语法

select s_score as firstscore from score where c_id=03 order by s_id limit 1;

7) last()

MS Access 支持 FIRST() 函数。MySql语法

select s_score as lastscore from score where c_id=03 order by s_id desc limit 1;/*desc降序*/

8) field()返回str在str1,str2,STR3,…列表中的索引(从1开始的位置)

select field('c','a','b','c');

9) sqrt开平方函数

10) mod 求余数

3.字符串函数

1) lower() lcase()字母转换成小写

select lower('ASDFDF');
select lcase('ASDFDF');

2) upper() ucase()字母转换成小写

select upper('hfhhg');
select ucase('ghghgh');

3) mid()&substr()提取函数,用于从文本字段中提取字符。

-- SELECT MID(column_name,start[,length]) FROM table_name;
select s_name,mid(s_birthday,6) as monday from student;
select s_name,mid(s_birthday,6,2) as mon from student;select substr(create_time,6,5) from t_orders
select substr(create_time from 6 for 5) from t_orders

mid()&substr()用途一致,sunstr()有更多的写法

4) len()返回文本字段中值的长度。

select s_name,length(s_birthday) as len from student;

5) concat()函数连接字符串

select concat('aa','bb','12') as con;
select concat('aa','bb',null) as con;#如有任何一个参数为NULL ,则返回值为 NULL

#如果自变量中含有任一二进制字符串,则结果为一个二进制字符串。
– concat_ws()以特定分隔符连接 一个数字参数被转化为与之相等的二进制字符串格式;若要避免这种情况,可使用显式类型 cast

select concat_ws('#','aa','bb','12') as con;
select concat_ws(null,'aa','bb','12') as con;#分隔符为 NULL,则结果为 NULL
select concat_ws('#','aa','bb',null) as con;#忽略任何分隔符参数后的 NULL 值

4.数据类型转换函数

1) CAST()

CAST() 函数语法如下:
CAST (<expression> AS <data_ type>[ length ])

select CAST(create_time AS CHAR(20)) from t_orders

其中 <data_ type>可以有:

  • 二进制,同带binary前缀的效果 : BINARY
  • 字符型,可带参数 : CHAR()
  • 日期 : DATE
  • 时间: TIME
  • 日期时间型 : DATETIME
  • 浮点数 : DECIMAL
  • 整数 : SIGNED
  • 无符号整数 : UNSIGNED

2) CONVERT()

CONVERT()函数语法如下:
CONVERT( <expression>,<data_ type>[ length ])

select CONVERT(create_time , CHAR(20)) from t_orders

5.通用函数

1)IFNULL()和COALESCE()

COALESCE(value,…)
可用于多种数据库
返回第一个不是null的值,如果参数列表全是null,则返回null

IFNULL(expression,alt_value)
用于mysql(oracle是 nvl)
如果expression是null,那就返回alt_value

6.窗口函数

语法:

<窗口函数> over ([PARTITION by <列清单>] Order by <排序用列清单>)

注意:mysql中会改变结果的排序展示

1).排序专用函数

常用场景:

-- 分组排名
select *,
row_number() over (PARTITION by deptid Order by salary desc) AS RB,
rank() over (PARTITION by deptid Order by salary desc) AS RK,
dense_rank() over (PARTITION by deptid Order by salary desc) AS DR
from emp;-- 全表排名
select *,
row_number() over (Order by salary desc) AS ROWNUMBER
from emp;-- 分组TOPN
SELECT * FROM
(select *,row_number() over (PARTITION by deptid Order by salary desc) AS RBfrom emp
) A
WHERE A.RB<=2;-- 全表TOPN
SELECT * FROM
(select *,row_number() over (Order by salary desc) AS RBfrom emp
) A
WHERE A.RB<=2;
1) row_number()

不管是否排名一样,都按顺序1234

2) rank()

同名次数序号相同,下一个不连续,1224

3) dense_rank()

同名次数序号相同,下一个连续,1223

2)聚合函数类

A.普通SUM、MAX、MIN、AVG计算分组内本行及以上的聚合值

SELECT *,sum(score) over(PARTITION BY stuId ORDER BY courseId desc) as current_sum from score ;
SELECT *,sum(score) over(PARTITION BY stuId ORDER BY courseId asc ) as current_sum from score

举例

SELECT *,
sum(score) over(PARTITION BY stuId ORDER BY courseId ) as current_sum,
sum(score) over(PARTITION BY stuId) as current_sum2,
sum(score) over(ORDER BY stuId ) as current_sum3
from score ;

B.移动计算
n PRECEDING --上n行
n FOLLOWING --下n行

SELECT *,sum(score) over(PARTITION BY courseId ORDER BY stuId ASC ROWS 2 PRECEDING) as current_sum from score ;-- 本行及上两行的聚合值
SELECT *,sum(score) over(PARTITION BY courseId ORDER BY stuId ASC ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) as current_sum from score ;-- 本行及上1行和下1行的聚合值

3).取值函数

案例

【MySql】简明笔记相关推荐

  1. 一、Hive简明笔记

    目录 1.Hive基本概念 1.1 什么是Hive 1.2 Hive的优缺点 1.3 Hive架构原理 2.Hive安装 2.1 Hive安装部署 2.2 Hive元数据配置到MySQL 2.2.1 ...

  2. 字节跳动内部 MySQL 学习笔记火了,完整版开放下载!

    最近很多小伙伴找我要一些 MySQL 基础资料,于是我翻箱倒柜,把这份阿里大牛总结的 MySQL 归纳笔记找出来,免费共享给大家! 据说有小伙伴靠这份笔记顺利进入 BAT 哦,所以一定要好好学习这份资 ...

  3. 【mysql学习笔记整理】

    /*mysql学习笔记整理*/ /*常用的数据库操作对象*/ #库的操作 #创建 #数据库的创建 USE mysql; CREATE DATABASE db_x; #删除 #删除数据库 DROP DA ...

  4. MySQL自学笔记2--select的5个子句

    MySQL自学笔记 使用的MySQL自带命令客户端,其中具体的操作是在自建的数据库下room303表中进行的,表中的列有:id.name.age.email.tel.salary.riqi.class ...

  5. 命令行神器 Click 简明笔记

    Click Click 是用 Python 写的一个第三方模块,用于快速创建命令行.我们知道,Python 内置了一个 Argparse 的标准库用于创建命令行,但使用起来有些繁琐,Click 相比于 ...

  6. MySql入门笔记二~悲催的用户

    这些是当年小弟的MySql学习笔记,木有多么复杂的结构操作,木有多炫丽的语句开发,木有...总之就是木有什么技术含量... 日复一日,彪悍的人生伴随着彪悍的健忘,运维操作为王,好记性不如烂笔头,山水有 ...

  7. 初识mysql学习笔记

    使用VMVirtualBox导入Ubuntu后,可以通过sudo apt-get install mysql-server命令下载mysql. 在学习过程中,我遇到了连接不上Xshell的问题.最终在 ...

  8. MySQL学习笔记07【事务、用户管理和权限管理】

    MySQL 文档-黑马程序员(腾讯微云):https://share.weiyun.com/RaCdIwas 1-MySQL基础.pdf.2-MySQL约束与设计.pdf.3-MySQL多表查询与事务 ...

  9. MySQL学习笔记06【多表查询、子查询、多表查询练习】

    MySQL 文档-黑马程序员(腾讯微云):https://share.weiyun.com/RaCdIwas 1-MySQL基础.pdf.2-MySQL约束与设计.pdf.3-MySQL多表查询与事务 ...

  10. MySQL学习笔记05【多表操作、三大范式、数据库的备份和还原】

    MySQL 文档-黑马程序员(腾讯微云):https://share.weiyun.com/RaCdIwas 1-MySQL基础.pdf.2-MySQL约束与设计.pdf.3-MySQL多表查询与事务 ...

最新文章

  1. Subversion hooks脚本配置演示及排错
  2. 使用 create-react-app 构建 react应用程序 (react-scripts)
  3. 曹原25岁,今天第8篇Nature
  4. LeetCode Rotate Function(寻找规律)
  5. Docker部署微服务详解
  6. nodejs中的模块系统:exports导出模块
  7. JDK/Java 17 可能带来什么新特性?
  8. 张小娴的文章,喜欢的,贴来存档
  9. UVa 740 - Baudot Data Communication Code
  10. AD域中组织单位和组的区别
  11. bnuoj16491
  12. 计算机技术与软件专业技术资格(水平)考试指南
  13. 无线城市--WiMax,WiFi-Mesh和3G/4G/5g网络
  14. 【办公自动化Excel】开发工具的使用
  15. Cisco ❀ ICMP-互联网控制报文协议
  16. 用程序编写计算公式的高次方程数字计算机
  17. github clone 代码到本地全步骤
  18. thrift的使用介绍
  19. 怎么用matlab算磁滞,磁性材料磁化曲线和磁滞回线的Matlab绘制与拟合
  20. python之pool.apply_async

热门文章

  1. 绿盟漏扫使用手册_【技术干货】Oracle数据库漏洞扫描指南
  2. Qt嵌入式开发的初步认识
  3. 微信小程序开发笔记 支付篇③——微信支付JSAPI下单和微信小程序调起支付(V2版本)
  4. 企业加速推进数字化转型,程序员进国企靠谱吗?
  5. 华硕 ROG主题 提取主题包
  6. 2022-2028年全球与中国插座行业市场深度调研及投资预测分析
  7. css 剪辑图片_css如何截取图片?
  8. MFC应用程序“生死因果”内幕
  9. G++’s Family
  10. 《数据库》_考研复试_面试篇