SQL将查询出的多个列值合并为一个字符串

  • 使用group_concat函数。
MySQL [abook_resource]> select * from tag_country where tag_id = 1;
+----+--------+---------+-------------+
| id | tag_id | country | create_time |
+----+--------+---------+-------------+
|  3 |      1 | BR      |           0 |
|  1 |      1 | JP      |           0 |
+----+--------+---------+-------------+
2 rows in set (0.00 sec)

MySQL [abook_resource]> select country from tag_country where tag_id = 1;
+---------+
| country |
+---------+
| BR      |
| JP      |
+---------+

MySQL [abook_resource]> select *,group_concat(country) from tag_country group by tag_id;
+----+--------+---------+-------------+-----------------------+
| id | tag_id | country | create_time | group_concat(country) |
+----+--------+---------+-------------+-----------------------+
|  3 |      1 | BR      |           0 | BR,JP                 |
|  2 |      2 | CN      |           0 | CN                    |
+----+--------+---------+-------------+-----------------------+
2 rows in set (0.00 sec)

posted @ 2021-09-13 17:46  Gumi-21  阅读(513)  评论(0)    收藏  举报