当前位置:  开发笔记 > 后端 > 正文

是否可以将多行和表中的字符串连接到一个结果列中?

如何解决《是否可以将多行和表中的字符串连接到一个结果列中?》经验,为你挑选了1个好方法。



1> Jason S..:

见GROUP_CONCAT

例:

mysql> SELECT * FROM blah;
+----+-----+-----------+
| K  | grp | name      |
+----+-----+-----------+
|  1 |   1 | foo       |
|  2 |   1 | bar       |
|  3 |   2 | hydrogen  |
|  4 |   4 | dasher    |
|  5 |   2 | helium    |
|  6 |   2 | lithium   |
|  7 |   4 | dancer    |
|  8 |   3 | winken    |
|  9 |   4 | prancer   |
| 10 |   2 | beryllium |
| 11 |   1 | baz       |
| 12 |   3 | blinken   |
| 13 |   4 | vixen     |
| 14 |   1 | quux      |
| 15 |   4 | comet     |
| 16 |   2 | boron     |
| 17 |   4 | cupid     |
| 18 |   4 | donner    |
| 19 |   4 | blitzen   |
| 20 |   3 | nod       |
| 21 |   4 | rudolph   |
+----+-----+-----------+
21 rows in set (0.00 sec)

mysql> SELECT grp, GROUP_CONCAT(name ORDER BY K) FROM blah GROUP BY grp;
+-----+----------------------------------------------------------------+
| grp | GROUP_CONCAT(name ORDER BY K)                                  |
+-----+----------------------------------------------------------------+
|   1 | foo,bar,baz,quux                                               |
|   2 | hydrogen,helium,lithium,beryllium,boron                        |
|   3 | winken,blinken,nod                                             |
|   4 | dasher,dancer,prancer,vixen,comet,cupid,donner,blitzen,rudolph |
+-----+----------------------------------------------------------------+
4 rows in set (0.00 sec)

推荐阅读
linjiabin43
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有