码迷,mamicode.com
首页 > 数据库 > 详细

sql example 9 -- 子查询

时间:2015-06-14 21:12:27      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

sql example 9 – 子查询

sql example 9 – 子查询

数据库准备

create table student (
id int auto_increment primary key,
name varchar(10)
);

create table scores (
id int auto_increment PRIMARY key,
score int default 0,
foreign key (id) references student(id) on delete cascade on update cascade
);

子查询可以返回标量, 一行, 一列或者是子查询

select * from t1 where column1 = (select column1 from t2);

第一个 select 称为外查询, 第二个查询称为内查询, 也叫子查询

insert into student (name) values (‘a‘),(‘b‘),(‘c‘),(‘d‘),(‘e‘),(‘f‘),(‘g‘),(‘h‘),(‘i‘),(‘j‘),(‘k‘),(‘l‘),(‘m‘),(‘n‘);
insert into scores (score) values (60) ,(65) ,(71) ,(76) ,(88) ,(94) ,(68) ,(94) ,(66) ,(91) ,(61) ,(63) ,(92) ,(86);
select avg(score) from scores;
| avg(score) |
+------------+
|    76.7857 |
select round(avg(score), 2) from scores;
| round(avg(score), 2) |
+----------------------+
|                76.79 |
select id from scores where score >= 76.79;
| id |
+----+
|  5 |
|  6 |
|  8 |
| 10 |
| 13 |
| 14 |

现在要让上面两个查询合并成一个

select id from scores where score >= (select round(avg(score), 2) from scores);
| id |
+----+
|  5 |
|  6 |
|  8 |
| 10 |
| 13 |
| 14 |

这就是子查询.

子查询返回多个值的情况 使用 any, some, all 修饰 (any 和 some 等价)

select id from scores where score >= (select score from scores where id >= 9);

ERROR 1242 (21000): Subquery returns more than 1 row

select score from scores where id >= 9;
| score |
+-------+
|    66 |
|    91 |
|    61 |
|    63 |
|    92 |
|    86 |
select * from scores where score >= all (select score from scores where id >= 9);
| id | score |
+----+-------+
|  6 |    94 |
|  8 |    94 |
| 13 |    92 |
select * from scores where score >= any (select score from scores where id >= 9);
| id | score |
+----+-------+
|  2 |    65 |
|  3 |    71 |
|  4 |    76 |
|  5 |    88 |
|  6 |    94 |
|  7 |    68 |
|  8 |    94 |
|  9 |    66 |
| 10 |    91 |
| 11 |    61 |
| 12 |    63 |
| 13 |    92 |
| 14 |    86 |
select * from scores where score in (select score from scores where id >= 9);
select * from scores where score not in (select score from scores where id >= 9);
select * from scores where score != all (select score from scores where id >= 9);
| id | score |
+----+-------+
|  1 |    60 |
|  2 |    65 |
|  3 |    71 |
|  4 |    76 |
|  5 |    88 |
|  6 |    94 |
|  7 |    68 |
|  8 |    94 |
select exists (select score from scores where id >= 9);         # 有结果返回 1
select not exists (select score from scores where id >= 9);     # 无结果返回 1

sql example 9 -- 子查询

标签:

原文地址:http://www.cnblogs.com/sunznx/p/4575593.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!