比较两个表,并返回 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