MySQL查询在单行中用类似的字符将具有相似对应ID的记录连接起来
为此,可以将CONCAT_WS()与GROUP_CONCAT()一起使用。让我们先创建一个
mysql> create table DemoTable2016 -> ( -> UserId int, -> UserName varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable2016 values(1,'Chris'); mysql> insert into DemoTable2016 values(2,'Bob'); mysql> insert into DemoTable2016 values(1,'David'); mysql> insert into DemoTable2016 values(2,'Carol'); mysql> insert into DemoTable2016 values(1,'Sam');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable2016;
这将产生以下输出-
+--------+----------+ | UserId | UserName | +--------+----------+ | 1 | Chris | | 2 | Bob | | 1 | David | | 2 | Carol | | 1 | Sam | +--------+----------+ 5 rows in set (0.00 sec)
这是将记录连接在以特殊字符分隔的行中的查询-
mysql> select group_concat(concat_ws('-',UserName,UserId)) from DemoTable2016 group by UserId;这将产生以下输出-
+----------------------------------------------+
| group_concat(concat_ws('-',UserName,UserId)) |
+----------------------------------------------+
| Chris-1,David-1,Sam-1 |
| Bob-2,Carol-2 |
+----------------------------------------------+
2 rows in set (0.00 sec)热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志