Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select the longest text field when using GROUP BY in mysql, a la MAX()?

In MySql you can use the MAX() function to get the highest value when using GROUP BY, how can I do the same thing to get the longest string of text?

Sample table:

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.

The tricky part is that I want to ORDER BY id ASC to see the oldest entries on the top, and I want to group by the post_id which is not something that I can use to ORDER, and get the longest body.

Sample query:

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

Desired output:

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

Again the key is to select the longest body while maintaining the order based on the id.

like image 414
cwd Avatar asked Sep 03 '12 15:09

cwd


1 Answers

You need use CHAR_LENGTH instead of 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

You might want to see the difference: CHAR_LENGTH( ) vs LENGTH( )

SQLFiddle Demo

like image 138
John Woo Avatar answered Sep 21 '22 12:09

John Woo