我有一个包含三列的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行和最后两行进行文本group_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我也不知道最后两行怎么说。
有谁能帮我做一下MySQL查询吗?谢谢。
发布于 2014-02-20 03:43:33
您可以通过连接两个组级联的结果来做到这一点:
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;发布于 2014-02-20 02:38:03
UNION将二者结合;就像这样:
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 IDhttps://stackoverflow.com/questions/21896416
复制相似问题