Day 40 数据库查询语句

Day 40 数据库查询语句

添加数据补充

讲一个查询结果插入到另一张表中

create table tablename;
insert into tablename values();

create table tablename;
insert into tablename select * from tablename where 条件

所有select关键字

select * from tablename
	where
	group by
	having
	order by
	limit a,b

where条件

select * from tablename where 条件

where后面可以是:
比较运算符 > < >= <= = !=
成员运算符 in / not in	后面是一个set集合
逻辑预算符 and or not	not要放在表达式的前面,and和or放在两个表达式中间
区间 between a and b
模糊查询: like exists
	查询条件后加
    % 表示任意个数的任意字符
	_ 表示一个任意字符

distinct 取出重复记录

select distinct * from table_name;
# 仅档查询结果中所有字段全部相同时才算重复记录

选择字段

星号表示所有字段,可以手动指定字段,同时也可以使用四则运算(加减乘除),也可以使用聚合运算

指定别名

select 列名 as 别名 fromtablename where 条件
# as可以省略

统计函数(聚合函数)

将一堆数据经过计算得出一个结果

求和	sum(字段名)
平均数	avg(字段名)
最大值	max(字段名)
最小值	min(字段名)
个数	count(字段名)		#字段名可以为用*代替,如果列中有空 则不算个数

#查询某一列的平均值
select avg(列名) from table_name;

#如果需要同时展示这个最大/最小值对应的另一个字段的数据 

group by分组查询

将一个整体按照某个特征或依据来分成不同的部分

#统计字段个数
select 字段 count(*) from tablename group by 字段

#查询工资最高的人的姓名
#错误1 select name,max(salary) from emp;	#逻辑错误
#错误2 select name from emp where salary = max(salary);	#where 后面不能使用聚合函数
#可以使用子查询语句解决需求
select name,salary from emp where salary =(select max(salary) from emp)

having过滤

用于分组后过滤,与where的区别是having使用在分组之后

# 求出平均工资大于5000的部门
select dept,avg(salary) from emp group by having avg(salary) > 5000;

order by根据字段排序

select * from emp order by 字段 # 默认升序
select * from emp oeder by 字段 desc #降序
select * from emp order by 字段1 asc ,字段2 desc #多字段排序

limit用于限制要显示的记录数量

sekect * from table_name limit 起始位(默认0),个数

#经典的使用场景:分页显示

子查询

将一个查询语句的结果作为另一个查询语句的条件或是数据来源

in关键字查询

当内存查询(括号内的)结果会有多个结果时,不能使用=必须是in,另外子查询必须只能包含一列数据

exists关键字子查询

党内层查询有结果时,才会执行

select * from dept where exists(select * from dept where id=1)
#由于内存

笛卡尔积查询(内连接查询)

select * from table1,table2 where 条件;
# 笛卡尔积查询的结果会产生大量的关联错误的数据
# 会产生重复的字段信息没需要在select后制定需要查询的字段 并且通过where条件筛选

select * from table1 inner join table2 where 条件;
#这个是内连接查询,等同于笛卡尔积查询

左/右外连接查询

左边的表是信息无论是否能够匹配都要完整显示,右边的表仅展示匹配上的记录

select * from table1 left join table2 on 条件;

# 在外链接查询中不能使用where关键字,必须使用on专门来做表的对应关系

右外连接查询就是右边的表无论是否能够匹配都要完整显示,是哟恒=

方法类似左外连接查询

全外连接查询

无论是否匹配成功,两边的数据都要全部显示

select * from table1 full join table2 on 条件;

# mysql不支持全外连接茶轩
# mysql中我们可以将左右链接查询的结果合并 union

select * from table1 
union
select * from table2;
# union会自动去除重复的记录,union all不去重复

外连接查询是查到没有对应关系的数据,但是这样的数据根本就是有问题的,所以最常用的是内连接查询

内连接表示值显示匹配成功的,外连接显示没有匹配成功的也要显示

posted @ 2019-07-16 08:37  萨萌萌  阅读(172)  评论(0编辑  收藏  举报