首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >mysql:在mysql-column中查找最短和最长的值

mysql:在mysql-column中查找最短和最长的值
EN

Stack Overflow用户
提问于 2017-08-08 20:12:20
回答 3查看 956关注 0票数 2

我有一个关于在MySQL-Column "values“的连接字符串中找到最短和最长的值的问题。问题是,列中的值与"|“连接在一起,并且可能是不同的长度。

表:

代码语言:javascript
复制
ID  |  values 
----------------------------------------
A   |  12.1|11.23|134.44
B   |  11.134|1.3|34.5|152.12|1.31313|134.331|12.31
C   |  34.11|1.34|343412.2|13......

问题是:是否有一些简单的可能性来找到这两个值(最短和最长)仅通过原生mysql查询,而不使用任何语言,如Java或PHP。

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-08-16 06:09:13

您不能在单个查询中获得所需的结果,至少在当前版本的MySQL中不能。原因是,在知道最大长度之前,您无法形成一个查询来从未知长度的分隔字符串中提取单个元素。

首先找出最长列表中有多少个元素:

代码语言:javascript
复制
select max(length(`values`)-length(replace(`values`, '|', ''))) as max from t;
+------+
| max  |
+------+
|    6 |
+------+

现在你知道你需要在你的分隔字符串中测试多达7个“字段”。没有办法形成具有可变数量的联合查询的SQL。语法必须在准备时固定,所以你需要知道有多少。

代码语言:javascript
复制
select id, substring_index(substring_index(`values`, '|', 1), '|', -1) as element from t
union
select id, substring_index(substring_index(`values`, '|', 2), '|', -1) from t
union
select id, substring_index(substring_index(`values`, '|', 3), '|', -1) from t
union
select id, substring_index(substring_index(`values`, '|', 4), '|', -1) from t
union
select id, substring_index(substring_index(`values`, '|', 5), '|', -1) from t
union
select id, substring_index(substring_index(`values`, '|', 6), '|', -1) from t
union
select id, substring_index(substring_index(`values`, '|', 7), '|', -1) from t;    

+------+----------+
| id   | element  |
+------+----------+
| A    | 12.1     |
| A    | 11.23    |
| A    | 134.44   |
| B    | 11.134   |
| B    | 1.3      |
| B    | 34.5     |
| B    | 152.12   |
| B    | 1.31313  |
| B    | 134.331  |
| B    | 12.31    |
| C    | 34.11    |
| C    | 1.34     |
| C    | 343412.2 |
| C    | 13       |
+------+----------+

现在使用上面的查询作为子查询,您可以找到最长或最短的查询:

代码语言:javascript
复制
(select id, element from (...subquery...) as t1 order by length(element) asc limit 1)
union
(select id, element from (...subquery...) as t2 order by length(element) desc limit 1)

+------+----------+
| id   | element  |
+------+----------+
| C    | 343412.2 |
| C    | 13       |
+------+----------+

我同意其他人的意见,即这确实是使用RDBMS的错误方式。我知道你说过你致力于这个结构,但从长远来看,你会发现它为你带来了比修复模式更多的工作。

另请参阅我对Is storing a delimited list in a database column really that bad?的回答

票数 1
EN

Stack Overflow用户

发布于 2017-08-08 20:19:37

最大长度

代码语言:javascript
复制
select * from table order by length(column_name) DESC LIMIT 0,1

最小长度

代码语言:javascript
复制
select * from table order by length(column_name) ASC LIMIT 0,1

如果这不是您要查看的内容,请将SQL查询添加到问题中。

票数 1
EN

Stack Overflow用户

发布于 2017-08-16 05:20:56

SQL对单元格中值的数组不友好。重新构造模式,那么解决方案就很简单了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45568042

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档