当前位置:Gxlcms > 数据库问题 > sql example 9 -- 子查询

sql example 9 -- 子查询

时间:2021-07-01 10:21:17 帮助过:2人阅读

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 -- 子查询

标签:

人气教程排行