前几行和最后几行的MySQL Group_concat

时间:2014-02-20 01:46:37

标签: mysql group-concat

我有一个包含三列的MySQL表,如下所示:

    ID  Line    Text
    1001    1   Line 1 Text
    1001    2   Line 2 Text
    1001    3   Line 3 Text
    1001    4   Line 4 Text
    1001    5   Line 5 Text
    1001    6   Line 6 Text
    1002    1   Line 1 Text
    1002    2   Line 2 Text
    1002    3   Line 3 Text
    1002    4   Line 4 Text
    1002    5   Line 5 Text
    1002    6   Line 6 Text     
    1002    7   Line 7 Text

每个ID的最小行数可能不同(可能高达100)但每个ID至少有6行。

我想通过仅为每个ID获取前3行和最后两行来执行text_concat,如下所示:

    ID     Text
    1001    Line 1 Text Line 2 Text Line 3 Text Line 5 Text Line 6 Text
    1002    Line 1 Text Line 2 Text Line 3 Text Line 6 Text Line 7 Text

当我想在所有行上执行group_concat时,我使用以下代码:

    SELECT ID, GROUP_CONCAT(Text SEPARATOR ' ') AS textConcat
    FROM table
    GROUP BY ID

如果我只想提取前3行,我可能会把where条件设置如下:

    SELECT ID, GROUP_CONCAT(Text SEPARATOR ' ') AS textConcat
    FROM table
    WHERE Line <= 3
    GROUP BY ID

我不知道如何获得最后两行

有人可以帮我解决这个问题吗?谢谢。

2 个答案:

答案 0 :(得分:1)

您可以通过连接两个组concats的结果来完成此操作:

SELECT ID,
       concat(substring_index(GROUP_CONCAT(Text SEPARATOR ' '), ' ', 3),
              substring_index(GROUP_CONCAT(Text SEPARATOR ' '), ' ', -2)
             ) as textConcat
FROM table
GROUP BY ID;

如果行很长,它们确实存在溢出group_concat()的默认字符串大小的风险。

你也可以这样做:

select t.id, group_concat(t.line separator ' ' order by t.id) as lines
from table t join
     (select id, max(line) as numlines
      from table t
      group by id
     ) tl
     on t.id = tl.id
where t.line <= 3 or t.line > t.numlines - 2;

答案 1 :(得分:0)

  1. 获取前3行和后2行;
  2. UNION;
  3. 组合它们
  4. 执行文本的group_concat。
  5. 就像这样:

    SELECT ID, GROUP_CONCAT(Text ORDER BY ID, Line SEPARATOR ' ') AS textConcat
    FROM
    (
        SELECT ID, Line, Text
        FROM table
        WHERE Line <= 3
    
    UNION
    
        SELECT ID, Line, Text
        FROM table t1
        WHERE EXISTS (SELECT COUNT(*) FROM table t2 WHERE t1.ID = t2.ID AND t1.Line < t2.Line HAVING Count(*) < 2)
    ORDER BY id, line
        ) TEMP
    GROUP BY ID
    

    SQL Fiddle

相关问题