MySQL(2):SQL进阶
一、数据库相关理论
1、系统数据库
information_schema: 虚拟库,不占用磁盘空间,存储的是数据库启动后的一些参数,如用户表信息、列信息、权限信息、字符信息等
performance_schema: mysql 5.5开始新增一个数据库:主要用于收集数据库服务器性能参数,记录处理查询请求时发生的各种事件、锁等现象
mysql: 授权库,主要存储系统用户的权限信息
test: mysql数据库系统自动创建的测试数据库
2、创建库
1 语法(help create database)
create database 数据库名 charset utf8;
2 数据库命名规则:
可以由字母、数字、下划线、@、#、$ 区分大小写 唯一性 不能使用关键字如 create select 不能单独使用数字 最长128位
3、库相关操作
详细见 sql(1)初识sql
二、表相关理论
表的本质即为 ‘文件’
1、存储引擎
文件(表)的类型在mysql中称之为存储引擎
不同的类型会对应不同的处理机制
''' sql底层流程原理: 1、一堆接口(python、perl、ruby等等) 2、连接池(并发,为了机器的负载均衡引入池) 3、sql接口(数据库操作命令,存储过程,视图,触发器等等) 4、解析器(sql语句(有执行优先级之分),查询\事务) 5、优化查询(索引技术,最少的io) 6、缓存\缓冲池(内存空间,存储常用的数据,提升速度) 7、存储引擎 myisam innodb 支持事务,行锁,支持外键 memory 内存 8、文件系统 '''
查看存储引擎 图
2、表操作之约束条件
约束条件与数据类型的宽度一样,是可选参数
作用:用于保证数据的完整性和一致性
# primary key (pk) 标识该字段为该表的主键,可以唯一的标识记录 # foreign key (fk) 标识该字段为该表的外键 # not null 标识该字段不能为空 # unique key (uk) 标识该字段的值是唯一的 # auto_increment 标识该字段的值自动增长(整数类型,而且为主键) # default 为该字段设置默认值 # unsigned 无符号 # zerofill 使用0填充
说明:
1. 是否允许为空,默认null,可设置not null,字段不允许为空,必须赋值 2. 字段是否有默认值,缺省的默认值是null,如果插入记录时不给字段赋值,此字段使用默认值 sex enum('male','female') not null default 'male' age int unsigned not null default 20 必须为正值(无符号) 不允许为空 默认是20 3. 是否是key 主键 primary key 外键 foreign key 索引 (index,unique...)
2.1 not null 和 default
是否可空,null表示空,非字符串
not null - 不可空
null - 可空
默认值,创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值
create table tb1(
nid int not null defalut 2,
num int not null
)
==================not null==================== mysql> create table t1(id int); #id字段默认可以插入空 mysql> desc t1; +-------+---------+------+-----+---------+-------+ | field | type | null | key | default | extra | +-------+---------+------+-----+---------+-------+ | id | int(11) | yes | | null | | +-------+---------+------+-----+---------+-------+ mysql> insert into t1 values(); #可以插入空 mysql> create table t2(id int not null); #设置字段id不为空 mysql> desc t2; +-------+---------+------+-----+---------+-------+ | field | type | null | key | default | extra | +-------+---------+------+-----+---------+-------+ | id | int(11) | no | | null | | +-------+---------+------+-----+---------+-------+ mysql> insert into t2 values(); #不能插入空 error 1364 (hy000): field 'id' doesn't have a default value ==================default==================== #设置id字段有默认值后,则无论id字段是null还是not null,都可以插入空,插入空默认填入default指定的默认值 mysql> create table t3(id int default 1); mysql> alter table t3 modify id int not null default 1; ==================综合练习==================== mysql> create table student( -> name varchar(20) not null, -> age int(3) unsigned not null default 18, -> sex enum('male','female') default 'male', -> hobby set('play','study','read','music') default 'play,music' -> ); mysql> desc student; +-------+------------------------------------+------+-----+------------+-------+ | field | type | null | key | default | extra | +-------+------------------------------------+------+-----+------------+-------+ | name | varchar(20) | no | | null | | | age | int(3) unsigned | no | | 18 | | | sex | enum('male','female') | yes | | male | | | hobby | set('play','study','read','music') | yes | | play,music | | +-------+------------------------------------+------+-----+------------+-------+ mysql> insert into student(name) values('mogu'); mysql> select * from student; +------+-----+------+------------+ | name | age | sex | hobby | +------+-----+------+------------+ | mogu | 18 | male | play,music | +------+-----+------+------------+
2.2 unique key
============设置唯一约束 unique=============== 方法一: create table department1( id int, name varchar(20) unique, comment varchar(100) ); 方法二: create table department2( id int, name varchar(20), comment varchar(100), constraint uk_name unique(name) ); mysql> insert into department1 values(1,'it','技术'); query ok, 1 row affected (0.00 sec) mysql> insert into department1 values(1,'it','技术'); error 1062 (23000): duplicate entry 'it' for key 'name'
create table service( id int primary key auto_increment, name varchar(20), host varchar(15) not null, port int not null, unique(host,port) #联合唯一 ); mysql> insert into service values -> (1,'nginx','192.168.0.10',80), -> (2,'haproxy','192.168.0.20',80), -> (3,'mysql','192.168.0.30',3306) -> ; query ok, 3 rows affected (0.01 sec) records: 3 duplicates: 0 warnings: 0 mysql> insert into service(name,host,port) values('nginx','192.168.0.10',80); error 1062 (23000): duplicate entry '192.168.0.10-80' for key 'host'
2.3 primary key
从约束角度看primary key字段的值不为空且唯一,那我们直接使用not null+unique不就可以了吗,要它干什么?
主键primary key是innodb存储引擎组织数据的依据,innodb称之为索引组织表,一张表中必须有且只有一个主键。
一个表中可以:
单列做主键
多列做主键(复合主键)
============单列做主键=============== #方法一:not null+unique create table department1( id int not null unique, #主键 name varchar(20) not null unique, comment varchar(100) ); mysql> desc department1; +---------+--------------+------+-----+---------+-------+ | field | type | null | key | default | extra | +---------+--------------+------+-----+---------+-------+ | id | int(11) | no | pri | null | | | name | varchar(20) | no | uni | null | | | comment | varchar(100) | yes | | null | | +---------+--------------+------+-----+---------+-------+ rows in set (0.01 sec) #方法二:在某一个字段后用primary key create table department2( id int primary key, #主键 name varchar(20), comment varchar(100) ); mysql> desc department2; +---------+--------------+------+-----+---------+-------+ | field | type | null | key | default | extra | +---------+--------------+------+-----+---------+-------+ | id | int(11) | no | pri | null | | | name | varchar(20) | yes | | null | | | comment | varchar(100) | yes | | null | | +---------+--------------+------+-----+---------+-------+ rows in set (0.00 sec) #方法三:在所有字段后单独定义primary key create table department3( id int, name varchar(20), comment varchar(100), constraint pk_name primary key(id); #创建主键并为其命名pk_name mysql> desc department3; +---------+--------------+------+-----+---------+-------+ | field | type | null | key | default | extra | +---------+--------------+------+-----+---------+-------+ | id | int(11) | no | pri | null | | | name | varchar(20) | yes | | null | | | comment | varchar(100) | yes | | null | | +---------+--------------+------+-----+---------+-------+ rows in set (0.01 sec)
==================多列做主键================ create table service( ip varchar(15), port char(5), service_name varchar(10) not null, primary key(ip,port) ); mysql> desc service; +--------------+-------------+------+-----+---------+-------+ | field | type | null | key | default | extra | +--------------+-------------+------+-----+---------+-------+ | ip | varchar(15) | no | pri | null | | | port | char(5) | no | pri | null | | | service_name | varchar(10) | no | | null | | +--------------+-------------+------+-----+---------+-------+ 3 rows in set (0.00 sec) mysql> insert into service values -> ('172.16.45.10','3306','mysqld'), -> ('172.16.45.11','3306','mariadb') -> ; query ok, 2 rows affected (0.00 sec) records: 2 duplicates: 0 warnings: 0 mysql> insert into service values ('172.16.45.10','3306','nginx'); error 1062 (23000): duplicate entry '172.16.45.10-3306' for key 'primary'
2.4 auto_increment
约束字段为自动增长,被约束的字段必须同时被key约束
#不指定id,则自动增长 create table student( id int primary key auto_increment, name varchar(20), sex enum('male','female') default 'male' ); mysql> desc student; +-------+-----------------------+------+-----+---------+----------------+ | field | type | null | key | default | extra | +-------+-----------------------+------+-----+---------+----------------+ | id | int(11) | no | pri | null | auto_increment | | name | varchar(20) | yes | | null | | | sex | enum('male','female') | yes | | male | | +-------+-----------------------+------+-----+---------+----------------+ mysql> insert into student(name) values -> ('egon'), -> ('alex') -> ; mysql> select * from student; +----+----------+------+ | id | name | sex | +----+----------+------+ | 1 | mogu | male | | 2 | xiaoming | male | +----+----------+------+ 2 rows in set (0.00 sec) #也可以指定id mysql> insert into student values (4,'xiaonvhai','female'); query ok, 1 row affected (0.01 sec) mysql> insert into student values (7,'xiaohuochai','male'); query ok, 1 row affected (0.00 sec) mysql> select * from student; +----+-------------+--------+ | id | name | sex | +----+-------------+--------+ | 1 | mogu | male | | 2 | xiaoming | male | | 4 | xiaonvhai | female | | 7 | xiaohuochai | male | +----+-------------+--------+ 4 rows in set (0.00 sec) #对于自增的字段,在用delete删除后,再插入值,该字段仍按照删除前的位置继续增长 mysql> delete from student; query ok, 4 rows affected (0.01 sec) mysql> select * from student; empty set (0.00 sec) mysql> insert into student (name) values ('zhangsan'); query ok, 1 row affected (0.01 sec) mysql> select * from student; +----+----------+------+ | id | name | sex | +----+----------+------+ | 8 | zhangsan | male | +----+----------+------+ 1 row in set (0.00 sec) #应该用truncate清空表,比起delete一条一条地删除记录,truncate是直接清空表,在删除大表时用它 mysql> truncate student; query ok, 0 rows affected (0.03 sec) mysql> insert into student (name) values ('lisi'); query ok, 1 row affected (0.01 sec) mysql> select * from student; +----+------+------+ | id | name | sex | +----+------+------+ | 1 | lisi | male | +----+------+------+ 1 row in set (0.00 sec)
#在创建完表后,修改自增字段的起始值 mysql> create table student( -> id int primary key auto_increment, -> name varchar(20), -> sex enum('male','female') default 'male' -> ); mysql> alter table student auto_increment=4;#修改起始值 mysql> show create table student; ....... engine=innodb auto_increment=3 default charset=utf8 mysql> insert into student (name)values('xiaomogu'); query ok, 1 row affected (0.01 sec) mysql> select * from student; +----+----------+------+ | id | name | sex | +----+----------+------+ | 4 | xiaomogu | male | +----+----------+------+ 1 row in set (0.00 sec) mysql> show create table student; ....... engine=innodb auto_increment=5 default charset=utf8 #也可以创建表时指定auto_increment的初始值,注意初始值的设置为表选项,应该放到括号外 create table student( id int primary key auto_increment, name varchar(20), sex enum('male','female') default 'male' )auto_increment=3;
2.5 foreign key 外键
一、 快速理解foreign key
员工信息表有三个字段:工号 姓名 部门
公司有3个部门,但是有1个亿的员工,那意味着部门这个字段需要重复存储,部门名字越长,越浪费
解决方法:
我们完全可以定义一个部门表
然后让员工信息表关联该表,如何关联,即foreign key
#表类型必须是innodb存储引擎,且被关联的字段,即references指定的另外一个表的字段,必须保证唯一 create table department( id int primary key, name varchar(20) not null )engine=innodb; #dpt_id外键,关联父表(department主键id),同步更新,同步删除 create table employee( id int primary key, name varchar(20) not null, dpt_id int, constraint fk_name foreign key(dpt_id) references department(id) on delete cascade on update cascade )engine=innodb; #先往父表department中插入记录 insert into department values (1,'欧德博爱技术有限事业部'), (2,'艾利克斯人力资源部'), (3,'销售部'); #再往子表employee中插入记录 insert into employee values (1,'egon',1), (2,'alex1',2), (3,'alex2',2), (4,'alex3',2), (5,'李坦克',3), (6,'刘飞机',3), (7,'张火箭',3), (8,'林子弹',3), (9,'加特林',3) ; #删父表department,子表employee中对应的记录跟着删 mysql> delete from department where id=3; mysql> select * from employee; +----+-------+--------+ | id | name | dpt_id | +----+-------+--------+ | 1 | egon | 1 | | 2 | alex1 | 2 | | 3 | alex2 | 2 | | 4 | alex3 | 2 | +----+-------+--------+ #更新父表department,子表employee中对应的记录跟着改 mysql> update department set id=22222 where id=2; mysql> select * from employee; +----+-------+--------+ | id | name | dpt_id | +----+-------+--------+ | 1 | egon | 1 | | 3 | alex2 | 22222 | | 4 | alex3 | 22222 | | 5 | alex1 | 22222 | +----+-------+--------+
二 、如何找出两张表之间的关系
分析步骤: #1、先站在左表的角度去找 是否左表的多条记录可以对应右表的一条记录,如果是,则证明左表的一个字段foreign key 右表一个字段(通常是id) #2、再站在右表的角度去找 是否右表的多条记录可以对应左表的一条记录,如果是,则证明右表的一个字段foreign key 左表一个字段(通常是id) #3、总结: #多对一: 如果只有步骤1成立,则是左表多对一右表 如果只有步骤2成立,则是右表多对一左表 #多对多 如果步骤1和2同时成立,则证明这两张表时一个双向的多对一,即多对多,需要定义一个这两张表的关系表来专门存放二者的关系 #一对一: 如果1和2都不成立,而是左表的一条记录唯一对应右表的一条记录,反之亦然。这种情况很简单,就是在左表foreign key右表的基础上,将左表的外键字段设置成unique即可
三、 建立表之间的关系
#一对多或称为多对一 三张表:出版社,作者信息,书 一对多(或多对一):一个出版社可以出版多本书 关联方式:foreign key
=====================多对一===================== create table press( id int primary key auto_increment, name varchar(20) ); create table book( id int primary key auto_increment, name varchar(20), press_id int not null, foreign key(press_id) references press(id) on delete cascade on update cascade ); insert into press(name) values ('北京工业地雷出版社'), ('人民音乐不好听出版社'), ('知识产权没有用出版社') ; insert into book(name,press_id) values ('九阳神功',1), ('九阴真经',2), ('九阴白骨爪',2), ('独孤九剑',3), ('降龙十巴掌',2), ('葵花宝典',3) ;
#多对多 三张表:出版社,作者信息,书 多对多:一个作者可以写多本书,一本书也可以有多个作者,双向的一对多,即多对多 关联方式:foreign key+一张新的表
=====================多对多===================== create table author( id int primary key auto_increment, name varchar(20) )engine=innodb default charset=utf8; create table book( id int primary key auto_increment, name varchar(10), type varchar(10) not null default '' )engine=innodb default charset=utf8; #这张表就存放作者表与书表的关系,即查询二者的关系查这表就可以了 create table author2book( id int not null unique auto_increment, author_id int not null, book_id int not null, constraint fk_author foreign key(author_id) references author(id) on delete cascade on update cascade, constraint fk_book foreign key(book_id) references book(id) on delete cascade on update cascade, primary key(author_id,book_id) ); #插入四个作者,id依次排开 insert into author(name) values('mogu'),('zhangsan'),('lisi'),('wangwu'); #每个作者与自己的代表作如下 1 mogu: 1 一千零一夜 2 安徒生童话 3 葫芦娃 4 变形金刚 5 七个小矮人 6 白雪公主 2 zhangsan: 1 一千零一夜 6 白雪公主 3 lisi: 4 变形金刚 5 七个小矮人 6 白雪公主 4 wangwu: 3 葫芦娃 insert into author2book(author_id,book_id) values (1,1), (1,2), (1,3), (1,4), (1,5), (1,6), (2,1), (2,6), (3,4), (3,5), (3,6), (4,3) ;
#一对一 两张表:学生表和客户表 一对一:一个学生是一个客户,一个客户有可能变成一个学校,即一对一的关系 关联方式:foreign key+unique
#一定是student来foreign key表customer,这样就保证了: #1 学生一定是一个客户, #2 客户不一定是学生,但有可能成为一个学生 create table customer( id int primary key auto_increment, name varchar(20) not null, qq varchar(10) not null, phone char(11) not null ); create table student( id int primary key auto_increment, class_name varchar(20) not null, customer_id int unique, #该字段一定要是唯一的 foreign key(customer_id) references customer(id) #外键的字段一定要保证unique on delete cascade on update cascade ); #增加客户 insert into customer(name,qq,phone) values ('小沫沫','31811231',13811341220), ('王三炮','123123123',15213146809), ('王山炮','283818181',1867141331), ('赵银宕','283818181',1851143312), ('王巴弹','888818181',1861243314), ('李大龙','112312312',18811431230) ; #增加学生 insert into student(class_name,customer_id) values ('全栈开发班',3), ('系统架构班',4), ('软件分析班',5) ;
三、单表查询
1、单表查询的语法
select 字段1,字段2... from 表名 where 条件 group by field having 筛选 order by field limit 限制条数
2、关键字的执行优先级(重点)
重点中的重点:关键字的执行优先级 from where group by having select distinct order by limit
1.找到表:from
2.拿着where指定的约束条件,去文件/表中取出一条条记录
3.将取出的一条条记录进行分组group by,如果没有group by,则整体作为一组
4.将分组的结果进行having过滤
5.执行select
6.去重
7.将结果按条件排序:order by
8.限制结果的显示条数
3、简单查询
company.employee 员工id id int 姓名 emp_name varchar 性别 sex enum 年龄 age int 入职日期 hire_date date 岗位 post varchar 职位描述 post_comment varchar 薪水 salary double 办公室 office int 部门编号 depart_id int #创建表 create table employee( id int not null unique auto_increment, name varchar(20) not null, sex enum('male','female') not null default 'male', #大部分是男的 age int(3) unsigned not null default 28, hire_date date not null, post varchar(50), post_comment varchar(100), salary double(15,2), office int, #一个部门一个屋子 depart_id int ); #查看表结构 mysql> desc employee; +--------------+-----------------------+------+-----+---------+----------------+ | field | type | null | key | default | extra | +--------------+-----------------------+------+-----+---------+----------------+ | id | int(11) | no | pri | null | auto_increment | | name | varchar(20) | no | | null | | | sex | enum('male','female') | no | | male | | | age | int(3) unsigned | no | | 28 | | | hire_date | date | no | | null | | | post | varchar(50) | yes | | null | | | post_comment | varchar(100) | yes | | null | | | salary | double(15,2) | yes | | null | | | office | int(11) | yes | | null | | | depart_id | int(11) | yes | | null | | +--------------+-----------------------+------+-----+---------+----------------+ #插入记录 #三个部门:教学,销售,运营 insert into employee(name,sex,age,hire_date,post,salary,office,depart_id) values ('egon','male',18,'20170301','老男孩驻沙河办事处外交大使',7300.33,401,1), #以下是教学部 ('alex','male',78,'20150302','teacher',1000000.31,401,1), ('wupeiqi','male',81,'20130305','teacher',8300,401,1), ('yuanhao','male',73,'20140701','teacher',3500,401,1), ('liwenzhou','male',28,'20121101','teacher',2100,401,1), ('jingliyang','female',18,'20110211','teacher',9000,401,1), ('jinxin','male',18,'19000301','teacher',30000,401,1), ('成龙','male',48,'20101111','teacher',10000,401,1), ('歪歪','female',48,'20150311','sale',3000.13,402,2),#以下是销售部门 ('丫丫','female',38,'20101101','sale',2000.35,402,2), ('丁丁','female',18,'20110312','sale',1000.37,402,2), ('星星','female',18,'20160513','sale',3000.29,402,2), ('格格','female',28,'20170127','sale',4000.33,402,2), ('张野','male',28,'20160311','operation',10000.13,403,3), #以下是运营部门 ('程咬金','male',18,'19970312','operation',20000,403,3), ('程咬银','female',18,'20130311','operation',19000,403,3), ('程咬铜','male',18,'20150411','operation',18000,403,3), ('程咬铁','female',18,'20140512','operation',17000,403,3) ; #ps:如果在windows系统中,插入中文字符,select的结果为空白,可以将所有字符编码统一设置成gbk
#简单查询 select id,name,sex,age,hire_date,post,post_comment,salary,office,depart_id from employee; select * from employee; select name,salary from employee; #避免重复distinct !!! select distinct post from employee; #通过四则运算查询 select name, salary*12 from employee; select name, salary*12 as annual_salary from employee; select name, salary*12 annual_salary from employee; #定义显示格式 concat() 函数用于连接字符串 select concat('姓名: ',name,' 年薪: ', salary*12) as annual_salary from employee; concat_ws() 第一个参数为分隔符 select concat_ws(':',name,salary*12) as annual_salary from employee; 结合case语句: select ( case when name = 'egon' then name when name = 'alex' then concat(name,'_bigsb') else concat(name, 'sb') end ) as new_name from emp;
4、where 约束
where字句中可以使用:
1. 比较运算符:> < >= <= <> !=
2. between 80 and 100 值在10到20之间
3. in(80,90,100) 值是10或20或30
4. like 'egon%'
pattern可以是%或_,
%表示任意多字符
_表示一个字符
5. 逻辑运算符:在多个条件直接可以使用逻辑运算符 and or not
#1:单条件查询 select name from employee where post='sale'; #2:多条件查询 select name,salary from employee where post='teacher' and salary>10000; #3:关键字between and select name,salary from employee where salary between 10000 and 20000; select name,salary from employee where salary not between 10000 and 20000; #4:关键字is null(判断某个字段是否为null不能用等号,需要用is) select name,post_comment from employee where post_comment is null; select name,post_comment from employee where post_comment is not null; select name,post_comment from employee where post_comment=''; 注意''是空字符串,不是null ps: 执行 update employee set post_comment='' where id=2; 再用上条查看,就会有结果了 #5:关键字in集合查询 select name,salary from employee where salary=3000 or salary=3500 or salary=4000 or salary=9000 ; select name,salary from employee where salary in (3000,3500,4000,9000) ; select name,salary from employee where salary not in (3000,3500,4000,9000) ; #6:关键字like模糊查询 通配符’%’ select * from employee where name like 'eg%'; 通配符’_’ select * from employee where name like 'al__';
5、分组查询:group by
#1、首先明确一点:分组发生在where之后,即分组是基于where之后得到的记录而进行的 #2、分组指的是:将所有记录按照某个相同字段进行归类,比如针对员工信息表的职位分组,或者按照性别进行分组等 #3、为何要分组呢? 取每个部门的最高工资 取每个部门的员工数 取男人数和女人数 小窍门:‘每’这个字后面的字段,就是我们分组的依据 #4、大前提: 可以按照任意字段分组,但是分组完毕后,比如group by post,只能查看post字段,如果想查看组内信息,需要借助于聚合函数
mysql> select @@global.sql_mode; +-------------------+ | @@global.sql_mode | +-------------------+ | | +-------------------+ 1 row in set (0.00 sec) mysql> select * from emp group by post; +----+------+--------+-----+------------+----------------------------+--------------+------------+--------+-----------+ | id | name | sex | age | hire_date | post | post_comment | salary | office | depart_id | +----+------+--------+-----+------------+----------------------------+--------------+------------+--------+-----------+ | 14 | 张野 | male | 28 | 2016-03-11 | operation | null | 10000.13 | 403 | 3 | | 9 | 歪歪 | female | 48 | 2015-03-11 | sale | null | 3000.13 | 402 | 2 | | 2 | alex | male | 78 | 2015-03-02 | teacher | null | 1000000.31 | 401 | 1 | | 1 | egon | male | 18 | 2017-03-01 | 老男孩驻沙河办事处外交大使 | null | 7300.33 | 401 | 1 | +----+------+--------+-----+------------+----------------------------+--------------+------------+--------+-----------+ 4 rows in set (0.00 sec) #由于没有设置only_full_group_by,于是也可以有结果,默认都是组内的第一条记录,但其实这是没有意义的 mysql> set global sql_mode='only_full_group_by'; query ok, 0 rows affected (0.00 sec) mysql> quit #设置成功后,一定要退出,然后重新登录方可生效 bye mysql> use db1; database changed mysql> select * from emp group by post; #报错 error 1055 (42000): 'db1.emp.id' isn't in group by mysql> select post,count(id) from emp group by post; #只能查看分组依据和使用聚合函数 +----------------------------+-----------+ | post | count(id) | +----------------------------+-----------+ | operation | 5 | | sale | 5 | | teacher | 7 | | 老男孩驻沙河办事处外交大使 | 1 | +----------------------------+-----------+ 4 rows in set (0.00 sec)
单独使用group by关键字分组 select post from employee group by post; 注意:我们按照post字段分组,那么select查询的字段只能是post,想要获取组内的其他相关信息,需要借助函数 group by关键字和group_concat()函数一起使用 select post,group_concat(name) from employee group by post;#按照岗位分组,并查看组内成员名 select post,group_concat(name) as emp_members from employee group by post; group by与聚合函数一起使用 select post,count(id) as count from employee group by post;#按照岗位分组,并查看每个组有多少人
ps:
如果我们用unique的字段作为分组的依据,则每一条记录自成一组,这种分组没有意义 多条记录之间的某个字段值相同,该字段通常用来作为分组的依据
聚合函数
#强调:聚合函数聚合的是组的内容,若是没有分组,则默认一组 示例: select count(*) from employee; select count(*) from employee where depart_id=1; select max(salary) from employee; select min(salary) from employee; select avg(salary) from employee; select sum(salary) from employee; select sum(salary) from employee where depart_id=3; #主要为5个: count、max、min、avg、sum
6、having 过滤
#! 执行优先级从高到低:where > group by > having
#1. where 发生在分组group by之前,因而where中可以有任意字段,但是绝对不能使用聚合函数。 #2. having发生在分组group by之后,因而having中可以使用分组的字段,无法直接取到其他字段,可以使用聚合函数
mysql> select @@sql_mode; +--------------------+ | @@sql_mode | +--------------------+ | only_full_group_by | +--------------------+ 1 row in set (0.00 sec) mysql> select * from emp where salary > 100000; +----+------+------+-----+------------+---------+--------------+------------+--------+-----------+ | id | name | sex | age | hire_date | post | post_comment | salary | office | depart_id | +----+------+------+-----+------------+---------+--------------+------------+--------+-----------+ | 2 | alex | male | 78 | 2015-03-02 | teacher | null | 1000000.31 | 401 | 1 | +----+------+------+-----+------------+---------+--------------+------------+--------+-----------+ 1 row in set (0.00 sec) mysql> select * from emp having salary > 100000; error 1463 (42000): non-grouping field 'salary' is used in having clause mysql> select post,group_concat(name) from emp group by post having salary > 10000;#错误,分组后无法直接取到salary字段 error 1054 (42s22): unknown column 'salary' in 'having clause' mysql> select post,group_concat(name) from emp group by post having avg(salary) > 10000; +-----------+-------------------------------------------------------+ | post | group_concat(name) | +-----------+-------------------------------------------------------+ | operation | 程咬铁,程咬铜,程咬银,程咬金,张野 | | teacher | 成龙,jinxin,jingliyang,liwenzhou,yuanhao,wupeiqi,alex | +-----------+-------------------------------------------------------+ 2 rows in set (0.00 sec)
7、order by 查询排序
# where > group by > having > distinct > order by
按单列排序 select * from employee order by salary; select * from employee order by salary asc; select * from employee order by salary desc; 按多列排序:先按照age排序,如果年纪相同,则按照薪资排序 select * from employee order by age, salary desc;
8、limit 限制查询数
示例: select * from employee order by salary desc limit 3; #默认初始位置为0 select * from employee order by salary desc limit 0,5; #从第0开始,即先查询出第一条,然后包含这一条在内往后查5条 select * from employee order by salary desc limit 5,5; #从第5开始,即先查询出第6条,然后包含这一条在内往后查5条
9、使用正则匹配
select * from employee where name regexp '^ale'; select * from employee where name regexp 'on$'; select * from employee where name regexp 'm{2}'; ^ 以什么开头 $ 以什么结尾 小结:对字符串匹配的方式 where name = 'mogu'; where name like 'yua%'; where name regexp 'on$';
select * from employee where name regexp '^jin.*[gn]$';
四、多表查询
#建表 create table department( id int, name varchar(20) ); create table employee( id int primary key auto_increment, name varchar(20), sex enum('male','female') not null default 'male', age int, dep_id int ); #插入数据 insert into department values (200,'技术'), (201,'人力资源'), (202,'销售'), (203,'运营'); insert into employee(name,sex,age,dep_id) values ('egon','male',18,200), ('alex','female',48,201), ('wupeiqi','male',38,201), ('yuanhao','female',28,202), ('liwenzhou','male',18,200), ('jingliyang','female',18,204) ;
1、多表链接语法
#重点:外链接语法 select 字段列表 from 表1 inner|left|right join 表2 on 表1.字段 = 表2.字段;
1.1 交叉连接:不适用任何匹配条件。生成笛卡尔积
mysql> select * from employee,department;
2.2 内连接:只连接匹配的行
找两张表共有的部分,相当于利用条件从笛卡尔积结果中筛选出了正确的结果 department没有204这个部门,因而employee表中关于204这条员工信息没有匹配出来 mysql> select employee.id,employee.name,employee.age,employee.sex,department.name from employee inner join department on employee.dep_id=department.id; #上述sql等同于 mysql> select employee.id,employee.name,employee.age,employee.sex,department.name from employee,department where employee.dep_id=department.id;
重点
1、inner join:只取两张表有对应关系的部分 select * from emp inner join dep on emp.dep_id = dep.id ; 2、left join:在inner join的基础上保留左表中的记录 select * from emp left join dep on emp.dep_id = dep.id ; 3、right join:在inner join的基础上保留右表中的记录 select * from emp right join dep on emp.dep_id = dep.id ; 4、full join:在内连接的基础上左右两边的记录都保留(在mysql中无‘full join’) select * from emp left join dep on emp.dep_id = dep.id union select * from emp right join dep on emp.dep_id = dep.id ;
2、符合条件链接查询
#示例1:以内连接的方式查询employee和department表,并且employee表中的age字段值必须大于25,即找出年龄大于25岁的员工以及员工所在的部门 select employee.name,department.name from employee inner join department on employee.dep_id = department.id where age > 25; #示例2:以内连接的方式查询employee和department表,并且以age字段的升序方式显示 select employee.id,employee.name,employee.age,department.name from employee,department where employee.dep_id = department.id and age > 25 order by age asc;
3、子查询
#1:子查询是将一个查询语句嵌套在另一个查询语句中。 #2:内层查询语句的查询结果,可以为外层查询语句提供查询条件。 #3:子查询中可以包含:in、not in、any、all、exists 和 not exists等关键字 #4:还可以包含比较运算符:= 、 !=、> 、<等
3.1、 带 in 关键字的子查询
#查询平均年龄在25岁以上的部门名 select id,name from department where id in (select dep_id from employee group by dep_id having avg(age) > 25); #查看技术部员工姓名 select name from employee where dep_id in (select id from department where name='技术'); #查看不足1人的部门名(子查询得到的是有人的部门id) select name from department where id not in (select distinct dep_id from employee);
3.2、 带比较运算符的子查询
#比较运算符:=、!=、>、>=、<、<=、<> #查询大于所有人平均年龄的员工名与年龄 mysql> select name,age from emp where age > (select avg(age) from emp); +---------+------+ | name | age | +---------+------+ | alex | 48 | | wupeiqi | 38 | +---------+------+ 2 rows in set (0.00 sec) #查询大于部门内平均年龄的员工名、年龄 select t1.name,t1.age from emp t1 inner join (select dep_id,avg(age) avg_age from emp group by dep_id) t2 on t1.dep_id = t2.dep_id where t1.age > t2.avg_age;
3.3 、带 exists 关键字的子查询
exists关字键字表示存在。在使用exists关键字时,内层查询语句不返回查询的记录。
而是返回一个真假值。true或false
当返回true时,外层查询语句将进行查询;当返回值为false时,外层查询语句不进行查询
#department表中存在dept_id=203,ture mysql> select * from employee -> where exists -> (select id from department where id=200); #department表中存在dept_id=205,false mysql> select * from employee -> where exists -> (select id from department where id=204); empty set (0.00 sec)
五、索引原理与sql 逻辑查询语句执行顺序
#索引的目的在于提高查询效率,与我们查阅图书所用的目录是一个道理:先定位到章,然后定位到该章下的一个小节,然后找到页数。相似的例子还有:查字典,查火车车次,飞机航班等
参考老师链接:
参考老师链接:sql逻辑查询语句执行顺序
上一篇: VR一体机如何退出FFBM
下一篇: 茂名周边自助旅游景点大全