最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
mysql中子查询学习笔记
时间:2014-10-16 编辑:简简单单 来源:一聚教程网
子查询最常用于SELECT-SQL命令的WHERE子句中。
子查询是一个 SELECT 语句,它嵌套在一个 SELECT、SELECT...INTO 语句、INSERT...INTO 语句、DELETE 语句、或 UPDATE 语句或嵌套在另一子查询中
子查询可以写在WHERE子句、HAVING子句、FROM子句中。
子查询分为多行子查询和单行子查询。
使用单行比较操作符:=、>、>=、<、<=、<>。
否则是多行子查询。
使用多行比较符:IN、> ANY 、> ALL、< ANY、< ALL。
单列子查询可以在DECODE和CASE语句,还有SELECT中除GROUP BY子句以外的所有子句中使用。
select t1.id 序号, t1.no 班级, t1.s_name 学生名字, t1.score 分数 from test_t t1 where (t1.id,t1.score) in (select t2.id, t2.score from test_t t2);
这里子查询返回两个列,但外层查询也要同时匹配这两个列。
单列子查询例子:
--查找表中分数最高的学生的名字和班级
select no 班级, s_name 学生名字 from test_t where score in(select max(score) from test_t);
班级 | 学生名字 |
2 | 李四 |
3 | 小C |
关联子查询按照一行接一行的顺序执行,主查询的每一行都执行一次子查询。
--查找每个班级中分数最高的学生的班级、名字和分数
INSERT INTO TEST_T (ID, NO, T_NAME, S_NAME, SCORE) VALUES ('10', '2', 'Mary', 'AAA', '70');
思路一(使用关联子查询):
select t1.id 序号, t1.no 班级, t1.s_name 学生名字, t1.score 分数 from test_t t1 where t1.score = (select max(t2.score) from test_t t2 where t1.no = t2.no);
查询结果:
序号 | 班级 | 学生名字 | 分数 |
2 | 2 | 李四 | 99 |
7 | 1 | Zhang | 70 |
6 | 3 | 小C | 99 |
1)先从外层查询的test_t t1表取出一行
ID | NO | T_NAME | S_NAME | SCORE |
1 | 1 | Peter | 张三 | 60 |
ID | NO | T_NAME | S_NAME | SCORE |
1 | 1 | Peter | 张三 | 60 |
4 | 1 | Peter | 小A | 59 |
7 | 1 | Peter | Zhang | 70 |
select t1.id 序号, t1.no 班级, t1.s_name 学生名字, t1.score 分数 from test_t t1 where t1.score = (select max(t2.score) from test_t t2) and t1.no = t2.no;
就会报错ORA-00904: "T2"."NO": 标识符无效
思路二(使用group by):
select id 序号, no 班级, s_name 学生名字, score 分数 from test_t where (no,score) in(select no 班级, max(score) 分数 from test_t group by no);
使用多列子查询,先在内层查询用班级号分组,算出最高分,返回给外层查询
1、如果在子查询中存在满足条件的行:
如果能找到一行,对于这个子查询来说,不继续查找,exists返回true。
继续下一个子查询。
如果没有一行满足子查询条件,子查询的查询结果为空,exists返回false。
继续下一个子查询。
TEST_T表。
select * from test_t t1 where exists (select 1 from test_t t2 where t2.score < 60 and t1.id = t2.id);
ID | NO | T_NAME | S_NAME | SCORE |
4 | 1 | Peter | 小A | 59 |
2)子查询只要找到一条满足条件的行,exists返回true,输出主查询的这一行
3)如果子查询结果为空,exists返回false,则不输出主查询的这一行
没有满足条件的行,返回true。
有满足条件的行,返回false。
如果子查询的结果都为空,那么会返回主查询的所有行。
select * from test_t t1 where not exists (select 1 from test_t t2 where t2.score < 90 and t1.id = t2.id);
ID | NO | T_NAME | S_NAME | SCORE |
6 | 3 | Tom | 小C | 99 |
2 | 2 | Mary | 李四 | 99 |
9 | 3 | Tom | Li | 90 |
相关文章
- MySQL登录、访问及退出操作解析 10-18
- sql语句 update字段null不能用is null问题解析 09-28
- SQL Server ISNULL 不生效原因及解决分析 09-28
- 关于if exists的用法及说明分析 09-28
- Access数据库日常维护方法 09-28
- Oracle 删除大量表记录操作介绍 09-27