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.
You need use
CHAR_LENGTHinstead ofLENGTHYou might want to see the difference: CHAR_LENGTH( ) vs LENGTH( )
SQLFiddle Demo