In this post we will see how we can produce the same result usingthe GROUP_CONCAT functionin MySQL.
Let us create the following table and data.
CREATE TABLE TestTable (ID INT, Col VARCHAR(4));
INSERT INTO TestTable (ID, Col)
SELECT 1, 'A'
UNION ALL
SELECT 1, 'B'
UNION ALL
SELECT 1, 'C'
UNION ALL
SELECT 2, 'A'
UNION ALL
SELECT 2, 'B'
UNION ALL
SELECT 2, 'C'
UNION ALL
SELECT 2, 'D'
UNION ALL
SELECT 2, 'E';
Now to generatecsvvalues of the column col for each ID, use the following code
SELECT ID, GROUP_CONCAT(col) AS CSV FROM TestTable
GROUP BY ID;The result is
ID CSV 1 A,B,C 2 A,B,C,D,E
You can also change the delimiters. Forexample insteadof comma, if you want to have a pipe symbol (|), use the following
SELECT ID, REPLACE(GROUP_CONCAT(col),',','|') AS CSV FROM TestTable
GROUP BY ID;The result is
ID CSV 1 A|B|C 2 A|B|C|D|E
MySQL makes this very simple withitssupport of GROUP_CONCAT function.
Reference: Pinal Dave (http://blog.sqlauthority.com)
Copyright © 2019- gamedaodao.com 版权所有 湘ICP备2022005869号-6
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务