MySQL全选,只有一列DISTINCT,同时还返回其他对应的列

时间:2019-03-25 19:39:16

标签: mysql

我有下表:

+-------------+---------------+------+-----+---------+----------------+
| Field       | Type          | Null | Key | Default | Extra          |
+-------------+---------------+------+-----+---------+----------------+
| id          | int(11)       | NO   | PRI | NULL    | auto_increment |
| name        | varchar(200)  | YES  |     | NULL    |                |
| department  | varchar(40)   | YES  |     | NULL    |                |
| type        | varchar(40)   | YES  |     | NULL    |                |
| description | varchar(1000) | YES  |     | NULL    |                |
| duration    | varchar(20)   | YES  |     | NULL    |                |
| start_date  | varchar(20)   | YES  |     | N/A     |                |
| study_mode  | varchar(9)    | YES  |     | NULL    |                |
| icon_url    | varchar(100)  | YES  |     | NULL    |                |
+-------------+---------------+------+-----+---------+----------------+

我想运行一个查询,该查询将输出每个部门,消除重复项,因为同一部门中可能有两个不同的课程。

enter image description here

图像中的查询本质上就是我想要的,唯一的问题是它输出的表2在每个字段中也只有空值。有没有办法我可以运行类似的查询,只输出t1?

当前查询:

SELECT * 
FROM `courses` AS t1 
LEFT JOIN `courses` AS t2 
ON t1.department = t2.department 
   AND t1.name < t2.name 
WHERE (t2.id IS NULL) AND (t1.type = 'Apprenticeship') 
ORDER BY t1.department\G

1 个答案:

答案 0 :(得分:1)

使用SELECT *代替SELECT t1.*

SELECT t1.* 
FROM `courses` AS t1 
LEFT JOIN `courses` AS t2 
ON t1.department = t2.department 
   AND t1.name < t2.name 
WHERE (t2.id IS NULL) AND (t1.type = 'Apprenticeship') 
ORDER BY t1.department