查询过滤重复数据:
查询排重:select distinct 列名 from 表名 where 条件;
聚集函数:
count 统计个数、sum求和、avg 平均值、max、min
在使用这几个函数进行数据的统计分析时,有时需要对数据表中的列进行数据的分组处理。
分组 group by :
排序:order by asc | desc;
内连接:
语法一:
select 列名 , 列名 .... from 表名1,表名2 where 表名1.列名 = 表名2.列名;
语法二:
select * from 表名 inner join 表名 on 条件
外连接查询
外链接:左外连接、右外连接、全连接、自连接。
左外链接:
左外连接:用左边表去右边表中查询对应记录,不管是否找到,都将显示左边表中全部记录。
语法:select * from 表1 left outer join 表2 on 条件;
select * from a left outer join b on a.A_ID = b.A_ID;
右外连接:
用右边表去左边表查询对应记录,不管是否找到,右边表全部记录都将显示
语法:select * from 表1 right outer join 表2 on 条件;
全连接:
全外连接:左外连接和右外连接的结果合并,单会去掉重复的记录。
select * from 表1 full outer join 表2 on 条件
select * from a full outer join b on a.A_ID = b.A_ID; 但是mysql数据库不支持此语法。
在sql语句全连接,其实就是左外链接和右外连接之和,去掉重复的数据。这时可以使用union
多表关系:
一对多 多对多 一对一
表的设计:需要引入外键约束
一对多:添加多的一方
多对多:创建第三张表
一对一:在任意一方都可以
多表查询:
内连接:
select * from a,b where a.a_id = b.a_id; (重点)
select * from a inner join b on a.a_id=b.a_id;
外连接:
左外连接:
select * from a left outer join b on a.a_id=b.a_id;
右外连接:
select * from a right outer join b on a.a_id=b.a_id;
关联子查询:一个查询作为另一个查询的一部分
in(子查询):在结果集中存在
select * from user where name ='张三' or name = '李四';
select * from user where name in ('张三','李四');
exists(子查询):子查询有结果,返回true,就显示
any/some: 任意一个(or)
yoursal > any(select sal from emp) ==> yoursal>sal1 or yousal>sal2 == > sal1>min(sal)
all:所有(and)