我有一个关于在MySQL-Column "values“的连接字符串中找到最短和最长的值的问题。问题是,列中的值与"|“连接在一起,并且可能是不同的长度。
表:
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。
谢谢
发布于 2017-08-16 06:09:13
您不能在单个查询中获得所需的结果,至少在当前版本的MySQL中不能。原因是,在知道最大长度之前,您无法形成一个查询来从未知长度的分隔字符串中提取单个元素。
首先找出最长列表中有多少个元素:
select max(length(`values`)-length(replace(`values`, '|', ''))) as max from t;
+------+
| max |
+------+
| 6 |
+------+现在你知道你需要在你的分隔字符串中测试多达7个“字段”。没有办法形成具有可变数量的联合查询的SQL。语法必须在准备时固定,所以你需要知道有多少。
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 |
+------+----------+现在使用上面的查询作为子查询,您可以找到最长或最短的查询:
(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?的回答
发布于 2017-08-08 20:19:37
最大长度
select * from table order by length(column_name) DESC LIMIT 0,1最小长度
select * from table order by length(column_name) ASC LIMIT 0,1如果这不是您要查看的内容,请将SQL查询添加到问题中。
发布于 2017-08-16 05:20:56
SQL对单元格中值的数组不友好。重新构造模式,那么解决方案就很简单了。
https://stackoverflow.com/questions/45568042
复制相似问题