比較兩個表,並返回 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)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP