您的位置:首页 > 数据库

sql 高级语法

2017-02-16 11:09 513 查看

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。



图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  三条语句的执行结果

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.



图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用法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: