天天看點

MySQL資料庫查詢資料操作篇第二十二篇子查詢

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      

繼續閱讀