Mysql DISTINCT not working if I add another column

喜夏-厌秋 提交于 2019-12-04 07:36:47

问题


mysql> select DISTINCT title, id from myadmins;

+------+------------+
| id   | title      |
+------+------------+
|    1 | admin      |
|    2 | stack      |
|    3 | jeff       |
|    4 | admin      |
|    5 | stack      |
+------+------------+
1 row in set (0.00 sec)

EDIT

What I want is not repeting the title column

+------+------------+
| id   | title      |
+------+------------+
|    2 | stack      |
|    3 | jeff       |
|    4 | admin      |
+------+------------+
1 row in set (0.00 sec)

回答1:


DISTINCT applies to the entire row of data. Since the ID is different on each row, then you will end up with duplicate titles.

If you need the ID, then you could use an aggregate to get the MAX(ID):

select max(id) id,
  title
from yourtable
group by title
order by id

See SQL Fiddle with Demo




回答2:


You will get distinct (id, title) couples.

The row with id=1 and title=admin is different from the row id=4 and title=admin.

If you want only distinct titles from your table:

select DISTINCT title from myadmins;

+------------+
| title      |
+------------+
| admin      |
| stack      |
| jeff       |
+------------+


来源:https://stackoverflow.com/questions/14430121/mysql-distinct-not-working-if-i-add-another-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!