union
查询多张表的结果,取并集,扩展行数。
如 select name from studentTable1
union select name from studentTable2
join
连接多张表中查询的结果,扩展列数。
SELECT * FROM Table1
JOIN Table2
ON Table1.ColumnA=Table2.columnA [where clause]
两个表见图1-1,三条左连接语句见下,结果见图1-2。
图1-1 两张表t1与t2
/*1*/SELECT table1.id as id,table1.theValue as value1,table2.theValue as value2 FROM `t1` as table1 left JOIN t2 as table2 on table1.id=table2.id;
/*2*/SELECT table1.id as id,table1.theValue as value1,(case WHEN table2.theValue is null then 0 else table2.theValue end) as value2 FROM `t1` as table1 left JOIN t2 as table2 on table1.id=table2.id;
/*3*/select id from(SELECT table1.id as id,table1.theValue as value1,(case WHEN table2.theValue is null then 0 else table2.theValue end) as value2 FROM `t1` as table1 left JOIN t2 as table2 on table1.id=table2.id) AS A WHERE (value1-value2)/value1 > 0.1;
图1-2 三条语句的执行结果
join
等价于 inner ,内连接。on 语句除了可以写 两个表的连接条件,还可以写类似where的单表字段的筛选条件。
inner join 下,过滤条件放在 ON 中或 WHERE 中,其返回的结果是一样的。
left join
等价于 left outer join,左(外)连接,以左边表为基准;
不管 ON 条件是否为真,数据库都会返回左侧表中的全部记录,相当于只增加了对于右侧表的过滤条件,而左侧表的内容,总是会全部返回的。
right join
等价于 right outer join,右(外)连接,以右边表为基准。
2.分组
Group By,分组。例 group by field1,依据field1字段的不同,将表划分成若干个“小区域”,然后针对这些“小区域”分别进行数据处理。
2.1 单个字段
group by 单个字段,见下。
图2-1 原始表
select 类别, sum(数量) as 数量之和
from A
group by 类别
图2-2 group by 之后的结果
没有聚合函数的时候使用group by field1,效果就是field1字段相同的数据只保留一条。
2.2 多个字段
group by 多个字段,见下。
例group by field1,field2, 这两个字段对应一致的数据才会进入同一个分组。
3.having
在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与聚合函数(如 min,sum等)一起使用。例子见图3-1.
图3-1 having用法
4. in 与 exists 的区别
in后面跟的是一个集合;exists 后面跟的是一个子查询,若查询到有行存在则输出父查询;
in 语句先执行子查询,将结果缓存;exists先执行父查询。
5.union与join
union
查询多张表的结果,取并集,扩展行数。
如 select name from studentTable1 union select name from studentTable2
join
连接多张表中查询的结果,扩展列数。
SELECT * FROM Table1 JOIN Table2 ON Table1.ColumnA=Table2.columnA
left join,左连接,以左边表为基准;
right join,右连接,以右边表为基准。
两个表见图5-1,三条左连接语句见下,结果见图4。
图5-1 两张表t1与t2
/*1*/SELECT table1.id as id,table1.theValue as value1,table2.theValue as value2 FROM `t1` as table1 left JOIN t2 as table2 on table1.id=table2.id;
/*2*/SELECT table1.id as id,table1.theValue as value1,(case WHEN table2.theValue is null then 0 else table2.theValue end) as value2 FROM `t1` as table1 left JOIN t2 as table2 on table1.id=table2.id;
/*3*/select id from(SELECT table1.id as id,table1.theValue as value1,(case WHEN table2.theValue is null then 0 else table2.theValue end) as value2 FROM `t1` as table1 left JOIN t2 as table2 on table1.id=table2.id) AS A WHERE (value1-value2)/value1 > 0.1;
图5-2 三条语句的执行结果
6.having
在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与聚合函数(如 min,sum等)一起使用。例子见图3.
图6-1 having用法