在MySql中,使用时,您可以使用MAX()函数来获取最大值GROUP BY,我该如何做同样的事情来获取最长的文本字符串?
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。
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。
id
您需要使用CHAR_LENGTH而不是LENGTH
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()