MYSQL - 查找不同的记录并按另一个字段长度排序

标签 mysql sql unique distinct

首先,感谢大家花时间帮助解决我的问题。

我有一个由idcontent组成的表格

一组示例数据是:

id  content
9   With astonishing insight and poignant precision
8   Whether they find themselves hacking rattles from the tails of snakes or nesting rattles in the hands of their babies.
4   This is a clear-eyed, deeply poignant collection.
12  This book is a dynamic compilation of snapshot tales, each of which encompasses its own sensory-rich world and can be read.
12  This book is an appropriate title for her collection-the prose poems feel revealed.
12  This book is a collection of ekphrastic vignettes set against surreal backdrops fraught with eerie characters faking normalcy.

我需要做的是找到每个唯一id的最短长度content

例如,上面的输出应该是:

id  content
9   With astonishing insight and poignant precision
8   Whether they find themselves hacking rattles from the tails of snakes or nesting rattles in the hands of their babies.
4   This is a clear-eyed, deeply poignant collection.
12  This book is an appropriate title for her collection-the prose poems feel revealed.

到目前为止,我所掌握的明显错误的是:

SELECT DISTINCT id, content FROM t
    GROUP BY id;

感谢您的帮助!

最佳答案

一种方法是计算最短长度,然后将结果连接回来:

select t.id, t.content
from (select id, min(length(content)) as minl
      from t
      group by id
     ) tmin join
     t
     on t.id = tmin.id and length(t.content) = tmin.minl;

注意:如果两个内容长度相同且均为最小值,则返回两者。您的问题没有指定在这种情况下该怎么做。

关于MYSQL - 查找不同的记录并按另一个字段长度排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26086102/

相关文章:

mysql - mysql 中的 GROUP BY 以 IS NULL 列为条件

mysql - 如何为 mysql 表中新列中的每一行生成唯一值?

python - 如何将一列中的所有列表编译成一个唯一列表

sql - 在 "removing"尾随空格后选择不同的

mysql - 简单的表查询

php - 向mysql数据库中两个(或多个)表插入数据的顺序

java - SQL 查询保证返回空

java - 如何将多个 MySql 连接查询转换为 Hibernate 查询?

sql - 除了参数之外,SQL 中的 @ 符号是什么?

mysql - 选择子组中的最新行