You can do this by concatenating the results of two group 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;
If the lines are long, they do run the risk of overflowing the default string size for group_concat()
.
You can also do this as:
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;