MySQL 中两个 select 之间的区别?

mysqlmysqli database

您可以使用子查询来计算 MySQL 中两个 select 之间的区别。语法如下:

SELECT *FROM yourTableName where yourColumnName NOT IN(SELECT yourColumnName FROM youTableName WHERE yourCondition;

为了理解上述语法,让我们创建一个表。创建表的查询如下:

mysql> create table DifferenceSelectDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> UserId int,
   -> UserValue int,
  -> PRIMARY KEY(Id)
   ->  );
Query OK, 0 rows affected (0.87 sec)

使用 insert 命令在表中插入一些记录。 查询语句如下:

mysql> insert into DifferenceSelectDemo(UserId,UserValue) values(10,10);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DifferenceSelectDemo(UserId,UserValue) values(10,20);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DifferenceSelectDemo(UserId,UserValue) values(20,30);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DifferenceSelectDemo(UserId,UserValue) values(20,20);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DifferenceSelectDemo(UserId,UserValue) values(30,40);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DifferenceSelectDemo(UserId,UserValue) values(30,20);
Query OK, 1 row affected (0.15 sec)

使用 select 语句显示表中的所有记录。查询如下:

mysql> select *from DifferenceSelectDemo;

输出结果如下:

+----+--------+-----------+
| Id | UserId | UserValue |
+----+--------+-----------+
|  1 |     10 |        10 |
|  2 |     10 |        20 |
|  3 |     20 |        30 |
|  4 |     20 |        20 |
|  5 |     30 |        40 |
|  6 |     30 |        20 |
+----+--------+-----------+
6 rows in set (0.02 sec)

以下是获取两个选择之间的差异的查询:

mysql> select *from DifferenceSelectDemo
   -> WHERE UserValue NOT IN (select UserValue from DifferenceSelectDemo where Id=1);

输出结果如下:

+----+--------+-----------+
| Id | UserId | UserValue |
+----+--------+-----------+
|  2 |     10 |        20 |
|  3 |     20 |        30 |
|  4 |     20 |        20 |
|  5 |     30 |        40 |
|  6 |     30 |        20 |
+----+--------+-----------+
5 rows in set (0.09 sec)

相关文章