MySQL查询计算文本字段中的最长行

时间:2015-04-17 12:28:03

标签: mysql

我在文本字段中显示了一些由换行符分隔的数据。对于每一行,我想获得该行中最长行的长度。

例如,如果一行包含以下数据

the cat\nsat on the\nmat

然后我想要一个返回10的查询,最长行的长度坐在'。

2 个答案:

答案 0 :(得分:2)

这里有一个想法......

为了便于阅读,在这个解决方案中,我用“|”代替了“\ n”。

请记住,仅仅因为你'可以',它不符合你'应该'!

SET @string = "the cat|sat on the|mat";

SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(@string,"|",i),"|",-1)x FROM ints;
+------------+
| x          |
+------------+
|            |
| the cat    |
| sat on the |
| mat        |
| mat        |
| mat        |
| mat        |
| mat        |
| mat        |
| mat        |
+------------+

SELECT LENGTH(SUBSTRING_INDEX(SUBSTRING_INDEX(@string,"|",i),"|",-1))x FROM ints ORDER BY x DESC LIMIT 1;
+------+
| x    |
+------+
|   10 |
+------+

答案 1 :(得分:1)

检查此sqlfiddle

CREATE TABLE tablename (
  id INT,
  name VARCHAR(50));

INSERT INTO tablename VALUES
  (1, 'the cat\nsat on the\nmat'),
  (2, 'd');

查询:

SELECT
max(length(SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, '\n', numbers.n), '\n', -1))) name
FROM
(SELECT 1 n UNION ALL SELECT 2
 UNION ALL SELECT 3 UNION ALL SELECT 4) numbers INNER JOIN tablename
   ON CHAR_LENGTH(tablename.name)
 -CHAR_LENGTH(REPLACE(tablename.name, '\n', ''))>=numbers.n-1
 ORDER BY
 id, n

结果:

name
 10

参考:here