MySQL 中的两个选择有什么区别?
您可以使用子查询来了解 MySQL 中两个选择之间的区别。语法如下
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)
广告