22.子查询
带any关键字子查询:
mysql> create table tbl1 (num1 int not null);
Query OK, 0 rows affected
mysql> create table tb12 (num int not null);
Query OK, 0 rows affected
mysql> insert into tbl1 values(1),(5),(13),(27);
Query OK, 4 rows affected
Records: 4 Duplicates: 0 Warnings: 0
mysql> insert into tb12 values(6),(14),(11),(20);
Query OK, 4 rows affected
Records: 4 Duplicates: 0 Warnings: 0
mysql> select num1 from tbl1 where num1 > any (select num from tb12);
+------+
| num1 |
+------+
| 13 |
| 27 |
| 14 |
| 11 |
| 20 |
+------+
5 rows in set
带all关键字子查询:
mysql> select num1 from tbl1 where num1 > all (select num from tb12);
+------+
| num1 |
+------+
| 27 |
+------+
1 row in set
带exists关键字子查询:
mysql> select * from suppliers;
+------+---------------+-----------+--------+--------+
| s_id | sname | s_city | s_zip | s_call |
+------+---------------+-----------+--------+--------+
| 1001 | fastfruit inc | tianjing | 30000 | 48075 |
| 1002 | lt supplies | chongqing | 40000 | 44332 |
| 1003 | acme | shanghai | 25809 | 90046 |
| 1004 | good boy | anqing | 528437 | 11123 |
| 1005 | oldboy | hefei | 246100 | 33322 |
+------+---------------+-----------+--------+--------+
5 rows in set
mysql> select * from fruits
-> where exists
-> (select sname from suppliers where s_id = 1001);
+------+------+--------+---------+
| f_id | s_id | f_name | f_price |
+------+------+--------+---------+
| a1 | 101 | apple | 5.2 |
| b1 | 102 | banana | 6.2 |
| c1 | 103 | caomei | 7.2 |
+------+------+--------+---------+
3 rows in set
带in关键字子查询:
mysql> select c_id from orders where o_num in
-> (select o_num from orderitems where f_id = "c0");
Empty set
mysql> select c_id from orders where o_num in (30003,30005);
Empty set
mysql> select c_id from orders where o_num not in
-> (select o_num from orderitems where f_id = "c0");
+------+
| c_id |
+------+
| 1001 |
| 1002 |
| 1003 |
+------+
3 rows in set
mysql> select * from orders;
+-------+---------------------+------+
| o_num | o_date | c_id |
+-------+---------------------+------+
| 3001 | 2019-12-11 00:00:00 | 1001 |
| 3002 | 2019-12-12 00:00:00 | 1002 |
| 3003 | 2019-12-13 00:00:00 | 1003 |
+-------+---------------------+------+
3 rows in set
带比较运算符的子查询:
mysql> select s_id,f_name from fruits
-> where s_id =
-> (select s1.s_id from suppliers as s1 where s1.s_city = "tianjin")
-> ;
Empty set
mysql> select s_id,f_name from fruits
-> where s_id <>
-> (select s1.s_id from suppliers as s1 where s1.s_city = "tianjin")
-> ;
Empty set
MySQL数据库查询数据操作篇第二十二篇子查询
原创
©著作权归作者所有:来自51CTO博客作者代码写注释的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
第二十二节 docker的图形化管理工具
docker图形化工具推荐
docker Docker 用户管理 -
Swift 周报 第二十二期
渺小不可怕,可怕的是比你优秀的强者还比你更加努力。Swift社区不会辜负每一位努力的勇士,优秀终将与你不期而遇!
Swift Apple iOS App 关键路径 -
MySQL数据库查询数据操作篇第二十一篇连接查询
MySQL数据库查询数据操作篇第二十一篇连接查询
mysql 字段 连接查询 -
nginx如何配置支持delete方法
nginx.conf文件的结构... #全局块 events{ #events块 ... } http{ #http块 ... #http全局块
nginx如何配置支持delete方法 Nginx 服务器 字符串