SQL查询以获取每个用户最长的昵称

时间:2019-06-09 13:57:18

标签: mysql

我有以下简单表格:

User Id    |    Nickname

1          |     abcdef
1          |     abdc
1          |     a

2          |     x
2          |     xyz
2          |     zyztx

一个用户可以有多个昵称。我想编写一个查询,为每个用户返回最长的昵称。我的查询应返回以下内容:

User Id    |    Nickname

1          |     abcdef

2          |     zyztx

如何编写这样的查询?

1 个答案:

答案 0 :(得分:0)

我个人认为这是微不足道的(但这对您来说是一种经验),可以通过使用相关的子查询来找到用户ID的最大长度并在where条件下使用来实现。

drop table if exists t;
create table t
(UserId  int  ,  Nickname varchar(20));
insert into t values
(1                   ,     'abcdef'), 
(1                   ,     'abdc' ),
(1                   ,     'a'),
(2                   ,     'x' ),
(2                   ,     'xyz'), 
(2                   ,     'zyztx');

select userid,nickname
from t
where length(nickname) = (select max(length(nickname)) from t t1 where t1.userid = t.userid);

+--------+----------+
| userid | nickname |
+--------+----------+
|      1 | abcdef   |
|      2 | zyztx    |
+--------+----------+
2 rows in set (0.00 sec)