为此,您可以将group_concat()与聚合函数一起使用。让我们首先创建一个表-
mysql> create table DemoTable1869 ( Id int, Subject varchar(20 ), Name varchar(20) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1869 values(100,'MySQL','John'); mysql> insert into DemoTable1869 values(100,'MongoDB','Smith'); mysql> insert into DemoTable1869 values(101,'MySQL','Chris'); mysql> insert into DemoTable1869 values(101,'MongoDB','Brown');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1869;
这将产生以下输出-
+------+---------+-------+ | Id | Subject | Name | +------+---------+-------+ | 100 | MySQL | John | | 100 | MongoDB | Smith | | 101 | MySQL | Chris | | 101 | MongoDB | Brown | +------+---------+-------+ 4 rows in set (0.00 sec)
这是查询以连接来自不同条件的同一列中的2个值-
mysql> select Id,concat(StudentFirstName,'',StudentLastName) from ( select Id, max(case when Subject='MySQL' then Name end) as StudentFirstName, max(case when Subject='MongoDB' then Name end) as StudentLastName from DemoTable1869 group by Id )tbl;
这将产生以下输出-
+------+---------------------------------------------+ | Id | concat(StudentFirstName,'',StudentLastName) | +------+---------------------------------------------+ | 100 | JohnSmith | | 101 | ChrisBrown | +------+---------------------------------------------+ 2 rows in set (0.00 sec)