MySQL 分组时如何从表格中选择最长的“字符串”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10882679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:38:52  来源:igfitidea点击:

How do I select the longest 'string' from a table when grouping

mysql

提问by user1336827

Example:

例子:

SELECT partnumber, manufacturer, condition, SUM(qty), AVG(price), description FROM parts

WHERE [something]

GROUP BY partnumber, manufacturer, condition

I have some descriptions that are blank, and there can be many partnumber, manufacturer, condition values, and on the group it seems to take the first description available, which can be blank. Id like to get the longest description available.

我有一些描述是空白的,可能有很多零件号、制造商、条件值,并且在组中似乎采用第一个可用的描述,它可以是空白的。我想获得最长的可用描述。

i tried this:

我试过这个:

MAX(LENGTH(description)) 

however that returns the number of characters in the string. Is it possible to do what im trying to do in MySQL?

但是,它返回字符串中的字符数。是否可以做我在 MySQL 中尝试做的事情?

回答by StilesCrisis

Try ORDER BY LENGTH(description) DESCand use LIMIT 1to only get the largest.

尝试ORDER BY LENGTH(description) DESC并使用LIMIT 1只获得最大的。

回答by Scott Nelson

ORDER BY LENGTH(description) DESC LIMIT 1

This will sort the results from longest to shortest and give the first result (longest.)

这会将结果从最长到最短排序,并给出第一个结果(最长)。

回答by eggyal

SELECT   partnumber, manufacturer, `condition`, SUM(qty), AVG(price), description
FROM     parts
WHERE    [something] AND LENGTH(description) = (
           SELECT MAX(LENGTH(description))
           FROM   parts AS p
           WHERE  p.partnumber   = parts.partnumber
              AND p.manufacturer = parts.manufacturer
              AND p.condition    = parts.condition
         )
GROUP BY partnumber, manufacturer, `condition`

回答by user1336827

It seems i answered my own question, MAX(description) seems to work just fine.

看来我回答了我自己的问题,MAX(description) 似乎工作得很好。

回答by Tushar Kesare

MAX(LENGTH(description)) returns length of longest value in Description column.

MAX(LENGTH(description)) 返回描述列中最长值的长度。