比較兩個表,並返回 MySQL 中丟失的 id?


若要比較兩張表並返回丟失的 id,您需要使用子查詢。語法如下 −

SELECT yourFirstTableName.yourIdColumnName FROM yourFirstTableName
WHERE NOT IN(SELECT yourSecondTableName.yourIdColumnName FROM youSecondTableName);

為了理解上述語法,讓我們建立一個帶有示例欄位的表,然後插入記錄。建立第一張表所用的查詢 −

First_Table

mysql> create table First_Table
   -> (
   -> Id int
   -> );
Query OK, 0 rows affected (0.88 sec)

現在使用 insert 命令在表中插入一些記錄。查詢如下 −

mysql> insert into First_Table values(1);
Query OK, 1 row affected (0.68 sec)
mysql> insert into First_Table values(2);
Query OK, 1 row affected (0.29 sec)
mysql> insert into First_Table values(3);
Query OK, 1 row affected (0.20 sec)
mysql> insert into First_Table values(4);
Query OK, 1 row affected (0.20 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下 −

mysql> select *from First_Table;

以下是輸出 −

+------+
| Id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
+------+
4 rows in set (0.00 sec)

以下是建立第二張表所用的查詢 −

Second_Table

mysql> create table Second_Table
   -> (
   -> Id int
   -> );
Query OK, 0 rows affected (0.60 sec)

現在可以使用 insert 命令在表中插入一些記錄。查詢如下 −

mysql> insert into Second_Table values(2);
Query OK, 1 row affected (0.19 sec)
mysql> insert into Second_Table values(4);
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement:
mysql> select *from Second_Table;

以下是輸出 −

+------+
| Id   |
+------+
|    2 |
|    4 |
+------+
2 rows in set (0.00 sec)

以下是用於比較兩張表並返回丟失 id 的查詢 −

mysql> select First_Table.Id from First_Table where
   -> First_Table.Id NOT IN(select Second_Table.Id from Second_Table);

以下是輸出 −

+------+
| Id   |
+------+
|    1 |
| 3 |
+------+
2 rows in set (0.00 sec)

更新於: 30-6-2020

1 千 + 次瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.