【问题标题】:mysql - select without duplicates for every value in column [duplicate]mysql - 为列中的每个值选择不重复的[重复]
【发布时间】:2020-08-30 07:09:31
【问题描述】:

我有一个如下所示的用户表。如何仅获取每个 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

【问题讨论】:

    标签: mysql sql database select greatest-n-per-group


    【解决方案1】:

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

    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
    

    【讨论】:

    • 我想接收每个用户名的所有唯一电子邮件值。此解决方案只会返回 id = '1' 的行。对于 AAA 用户名,它还应该返回 id = '5' 的行,因为 email 值是 other
    • 既然 karolo22 想要 AAA 的 id (1, 5),email 不会也包含在 partition by 语句中吗?
    • @karolo22 如果您使用的是GMB的第二个查询,您可以将partition by username更改为partition by username, email。这应该可以满足您的需求。
    • 也许第二个查询会起作用,但我有旧版本的 mysql - 5.7,我无法检查
    • @karolo22:好的。然后查看我编辑的答案。
    猜你喜欢
    • 2017-07-24
    • 1970-01-01
    • 2013-11-28
    • 2021-06-10
    • 1970-01-01
    • 2021-09-16
    • 2015-05-24
    • 2017-11-04
    • 1970-01-01
    相关资源
    最近更新 更多