12

在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.

4

2 回答 2

12

你需要使用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( )

SQLFiddle 演示

于 2012-09-03T15:25:58.917 回答
5
select p.post_id, p.title, p.body
from posts p
inner join (
  select post_id, max(length(body)) as MaxLength
  from posts
  group by post_id
) pm on p.post_id = pm.post_id and length(p.body) = MaxLength
order by p.id 

SQL 小提琴示例

于 2012-09-03T15:25:13.683 回答