MySQL 选择语句 SELECT DISTINCT 对于多列?


为了理解 MySQL 选择语句 SELECT DISTINCT 对于多列,我们来看一个示例并创建一个表。创建表的查询如下:

mysql> create table selectDistinctDemo
   -> (
   -> InstructorId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentId int,
   -> TechnicalSubject varchar(100)
   -> );
Query OK, 0 rows affected (0.50 sec)

使用插入命令向表中插入一些记录。查询如下:

mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'Java');
Query OK, 1 row affected (0.15 sec)
mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'MongoDB');
Query OK, 1 row affected (0.16 sec)
mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'MySQL');
Query OK, 1 row affected (0.15 sec)
mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(298,'Python');
Query OK, 1 row affected (0.11 sec)
mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(298,'SQL Server');
Query OK, 1 row affected (0.15 sec)
mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(397,'C#');
Query OK, 1 row affected (0.13 sec)

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

mysql> select *from selectDistinctDemo;

以下是输出

+--------------+-----------+------------------+
| InstructorId | StudentId | TechnicalSubject |
+--------------+-----------+------------------+
| 1            | 121       | Java             |
| 2            | 121       | MongoDB          |
| 3            | 121       | MySQL            |
| 4            | 298       | Python           |
| 5            | 298       | SQL Server       |
| 6            | 397       | C#               |
+--------------+-----------+------------------+
6 rows in set (0.00 sec)

以下是使用选择语句 SELECT DISTINCT 对于多列的查询

mysql> select InstructorId,StudentId,TechnicalSubject from selectDistinctDemo
-> where InstructorId IN
   -> (
   -> select max(InstructorId) from selectDistinctDemo
   -> group by StudentId
   -> )
-> order by InstructorId desc;

以下是输出

+--------------+-----------+------------------+
| InstructorId | StudentId | TechnicalSubject |
+--------------+-----------+------------------+
| 6            | 397       | C#               |
| 5            | 298       | SQL Server       |
| 3            | 121       | MySQL            |
+--------------+-----------+------------------+
3 rows in set (0.10 sec)

更新于:2019 年 7 月 30 日

511 次浏览

启动你的 事业

完成课程取得认证

开始
广告