使用不同条件将 MySQL 中同一列中的两个值连接起来
为此,可以使用带聚合函数的 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)
以下是将同一列中的 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)
广告