MySQL 中用于排除特定行的子查询

mysqlmysqli database更新于 2025/5/21 17:16:17

首先我们创建一个表 −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100),
   -> Age int
   -> );
Query OK, 0 rows affected (0.87 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable(Name,Age) values('John',21);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Name,Age) values('Carol',22);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Name,Age) values('David',23);
Query OK, 1 row affected (0.54 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

输出

这将产生以下输出 −

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  1 | John  | 21   |
|  2 | Carol |   22 |
|  3 | David |   23 |
+----+-------+------+
3 rows in set (0.00 sec)

以下是排除特定行的子查询,名称为 Carol −

mysql> select *from DemoTable
   -> where Name not in (select Name from DemoTable where Name='Carol'
   -> );

输出

这将产生以下输出 −

+----+-------+------+
| Id | Name  | Age  | 
+----+-------+------+
|  1 | John  | 21   |
|  3 | David |   23 |
+----+-------+------+
2 rows in set (0.00 sec)

相关文章


有用资源