SQL语句高级(三)——子查询

一、子查询(查询选秀3-245课程的成绩高于103号同学该门课程成绩的所有同学的记录)
mysql> select degree from score where sno = '103' and cno = '3-245';--先找到该成绩的值!!
+--------+
| degree |
+--------+
|     89 |
+--------+
1 row in set (0.00 sec)

mysql> select * from score 
    -> where cno='3-105'
    -> and 
    -> degree > (select degree from score where sno = '103' and cno = '3-245');

+-----+-------+--------+
| sno | cno   | degree |
+-----+-------+--------+
| 100 | 3-105 |    100 |
| 103 | 3-105 |     99 |
+-----+-------+--------+
2 rows in set (0.03 sec)

二、子查询(查询高于103号同学的3-245课程成绩的所有同学的成绩记录)
mysql> select * from score 
    -> where degree > (select degree from score where sno = '103' and cno = '3-245');
+-----+-------+--------+
| sno | cno   | degree |
+-----+-------+--------+
| 100 | 3-105 |    100 |
| 102 | 3-245 |    100 |
| 103 | 3-105 |     99 |
| 104 | 3-245 |     98 |
+-----+-------+--------+
4 rows in set (0.00 sec)

三、子查询(year函数和in关键字)
查询和100105这两位同学的出生年份相同的所有学生!
mysql> select * from student;
+-----+--------+---------------------+-------+-------+
| sno | sname  | sbirthday           | class | ssex  |
+-----+--------+---------------------+-------+-------+
| 100 | Java   | 1977-09-01 00:00:00 | 95033 | man   |
| 101 | C      | 1975-08-21 00:00:00 | 95034 | woman |
| 102 | C++    | 1976-02-11 00:00:00 | 95035 | woman |
| 103 | C#     | 1974-12-01 00:00:00 | 95034 | woman |
| 104 | Python | 1977-10-11 00:00:00 | 95033 | man   |
| 105 | JS     | 1974-11-11 00:00:00 | 95033 | woman |
+-----+--------+---------------------+-------+-------+
6 rows in set (0.09 sec)

mysql> select * from student where sno in (100,105);
+-----+-------+---------------------+-------+-------+
| sno | sname | sbirthday           | class | ssex  |
+-----+-------+---------------------+-------+-------+
| 100 | Java  | 1977-09-01 00:00:00 | 95033 | man   |
| 105 | JS    | 1974-11-11 00:00:00 | 95033 | woman |
+-----+-------+---------------------+-------+-------+
2 rows in set (0.04 sec)

mysql> select year(sbirthday) from student where sno in (100,105);
+-----------------+
| year(sbirthday) |
+-----------------+
|            1977 |
|            1974 |
+-----------------+
2 rows in set (0.08 sec)
mysql> select * from student 
    -> where year(sbirthday) in (select year(sbirthday) from student where sno in (100,105));
+-----+--------+---------------------+-------+-------+
| sno | sname  | sbirthday           | class | ssex  |
+-----+--------+---------------------+-------+-------+
| 100 | Java   | 1977-09-01 00:00:00 | 95033 | man   |
| 103 | C#     | 1974-12-01 00:00:00 | 95034 | woman |
| 104 | Python | 1977-10-11 00:00:00 | 95033 | man   |
| 105 | JS     | 1974-11-11 00:00:00 | 95033 | woman |
+-----+--------+---------------------+-------+-------+
4 rows in set (0.10 sec)

猜你喜欢

转载自blog.csdn.net/qq_37150711/article/details/87223927