MySQL 中排除特定行的子查詢


先建立一個表 -

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100),
   -> Age int
   -> );
Query OK, 0 rows affected (0.87 sec)

使用插入命令向表中插入一些記錄 -

mysql> insert into DemoTable(Name,Age) values('John',21);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Name,Age) values('Carol',22);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Name,Age) values('David',23);
Query OK, 1 row affected (0.54 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select *from DemoTable;

輸出

將生成以下輸出-

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  1 | John  | 21   |
|  2 | Carol |   22 |
|  3 | David |   23 |
+----+-------+------+
3 rows in set (0.00 sec)

以下是查詢中排除特定行的子查詢,即姓名為 Carol -

mysql> select *from DemoTable
   -> where Name not in (select Name from DemoTable where Name='Carol'
   -> );

輸出

將生成以下輸出-

+----+-------+------+
| Id | Name  | Age  | 
+----+-------+------+
|  1 | John  | 21   |
|  3 | David |   23 |
+----+-------+------+
2 rows in set (0.00 sec)

更新於: 30-06-2020

342 瀏覽數

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.