mysql - select 列中的每个值都没有重复项

mysql - select without duplicates for every value in column

我有一个用户 table,如下所示。我怎样才能只获得每个 username 的非重复记录?例如对于 username = AAA,我只想获取 id = '1'id ='5' 的行,对于 username = BBB,我只想获取 id = '2'.

的行
id     email            username
1      test1@test.com   AAA
2      test1@test.com   BBB
3      test2@test.com   CCC
4      test1@test.com   AAA
5      test2@test.com   AAA

您可以使用相关子查询进行过滤:

select t.*
from mytable t
where t.id = (
    select min(t1.id) 
    from mytable t1 
    where t1.username = t.username and t1.email = t.email
)

有了 (username, id) 上的索引,这应该是一个有效的解决方案。

如果你是 运行 MySQL 8.0,另一种选择是使用 row_number():

select id, email, username
from (
    select t.*, row_number() over(partition by username, email order by id) rn
    from mytable t
) t
where rn = 1