sql 高级语法

1. 并集与连接

1.1 union

查询多张表的结果,取并集,扩展行数。
如 select name from studentTable1 union select name from studentTable2

1.2 join

连接多张表中查询的结果,扩展列数。
SELECT * FROM Table1 JOIN Table2 ON Table1.ColumnA=Table2.columnA
left join,左连接,以左边表为基准;
right join,右连接,以右边表为基准。

两个表见图1-1,三条左连接语句见下,结果见图1-2。
sql 高级语法_第1张图片
图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;

sql 高级语法_第2张图片
图1-2  三条语句的执行结果

1.3 join 与 where

可以在join前用where先筛出来一部分,join 后再筛选一部分, 如:
select * from Student where age between 13 and 16 inner join Score where mathScore > 95 on Student.id=Score.id where Student.height > 170


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.

sql 高级语法_第3张图片

图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。
sql 高级语法_第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;

sql 高级语法_第5张图片
图5-2  三条语句的执行结果


6.having

在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与聚合函数(如 min,sum等)一起使用。例子见图3.

sql 高级语法_第6张图片

图6-1 having用法


你可能感兴趣的:(数据库)