在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)
阅读更多:MySQL 教程