在 MySQL 中将同一列中具有不同条件的两个值连接起来
mysqlmysqli database
为此,您可以将 group_concat() 与聚合函数结合使用。让我们首先创建一个表 −
mysql> create table DemoTable1869 ( Id int, Subject varchar(20 ), Name varchar(20) ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1869 values(100,'MySQL','John'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1869 values(100,'MongoDB','Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1869 values(101,'MySQL','Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1869 values(101,'MongoDB','Brown'); Query OK, 1 row affected (0.00 sec)
使用 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)
以下查询用于连接来自同一列且具有不同条件的两个值 −
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)