小编典典

在MySQL中使用GROUP BY时,如何选择最长的文本字段,即la MAX()?

sql

在MySql中,使用时,您可以使用MAX()函数来获取最大值GROUP BY,我该如何做同样的事情来获取最长的文本字符串?

样表:

id_|_post_id|_title__________|_body_____________________________________________
1  | ZXBF1J | Favorite Color | My favorite color is blue.
2  | ZXBF1J | Favorite Color | My favorite color is blue, no wait...
3  | ZXBF1J | Favorite Color | My favorite color is blue, no wait, yelloooow!
4  | AR3D47 | Quest          | To seek..
5  | AR3D47 | Quest          | To seek the Holy
6  | AR3D47 | Quest          | To seek the Holy Grail.

棘手的部分是,我想ORDER BY id ASC在顶部看到最旧的条目,并且要按进行分组,post_id这是我不能使用的ORDER,并且要获得最长的条目body

查询样例:

SELECT post_id, title, MAX(body) // obviously MAX() doesn't work here
FROM posts
GROUP BY post_id
ORDER BY id ASC

所需的输出:

post_id|_title__________|_body_____________________________________________
ZXBF1J | Favorite Color | My favorite color is blue, no wait, yelloooow!
AR3D47 | Quest          | To seek the Holy Grail.

再次,关键是要选择最长的body同时保持基于的顺序id


阅读 250

收藏
2021-05-16

共1个答案

小编典典

您需要使用CHAR_LENGTH而不是LENGTH

SELECT a.id, a.post_id, a.body
FROM posts a INNER JOIN
(
    SELECT post_ID, title, MAX(CHAR_LENGTH(body)) totalLength
    FROM posts
    GROUP BY post_ID, title
) b ON a.post_id = b.post_ID AND
        a.title = b.title AND
        CHAR_LENGTH(a.body) = b.totalLength

您可能想看看两者之间的区别:
CHAR_LENGTH()与LENGTH()

2021-05-16