當 MySQL 中的另一重複列值中找到某個重複的列值時,如何根據該列值排除行?


為此,你可以使用子查詢。我們首先建立一個 −

mysql> create table DemoTable1427
   -> (
   -> StudentId int,
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (1.28 sec)

使用插入在表中插入一些記錄 −

mysql> insert into DemoTable1427 values(201,89);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1427 values(201,99);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1427 values(210,98);
Query OK, 1 row affected (0.16 sec)

使用選擇從表中顯示所有記錄 −

mysql> select * from DemoTable1427 ;

這將產生以下輸出 −

+-----------+--------------+
| StudentId | StudentMarks |
+-----------+--------------+
|       201 |           89 |
|       201 |           99 |
|       210 |           98 |
+-----------+--------------+
3 rows in set (0.00 sec)

以下是對列值進行排除查詢,當另一個重複列值被找到時。此處,Studentmarks 89 使用 StudentId 201 並且該 Studentid 201 還有一個記錄,因此這兩個記錄將從結果中被排除 −

mysql> select * from DemoTable1427
   -> where StudentId NOT IN (select distinct StudentId from DemoTable1427 where StudentMarks=89);

這將產生以下輸出 −

+-----------+--------------+
| StudentId | StudentMarks |
+-----------+--------------+
|       210 |           98 |
+-----------+--------------+
1 row in set (0.00 sec)

更新於: 12-11-2019

437 次瀏覽

開啟您的職業生涯

完成課程後獲得認證

開始
廣告