将列值设置为MySQL查询结果中的列名?

要将列值设置为查询结果中的列名,您需要使用CASE语句。

语法如下-

select yourIdColumnName,
max(case when (yourColumnName1='yourValue1') then yourColumnName2 else NULL
end) as 'yourValue1',
max(case when (yourColumnName1='yourValue2') then yourColumnName2 else NULL
end) as 'yourValue2',
max(case when yourColumnName1='yourValue3') then yourColumnName2 else NULL
end) as 'yourValue3’,
.
.
N
from valueAsColumn
group by yourIdColumnName
order by yourIdColumnName;

为了理解上述语法,让我们创建一个表。创建表的查询如下-

mysql> create table valueAsColumn
   -> (
   -> UserId int,
   -> UserColumn1 varchar(10),
   -> UserColumn2 varchar(10)
   -> );

现在,您可以使用insert命令在表中插入一些记录。查询如下-

mysql> insert into valueAsColumn values(0,'John','A+');
mysql> insert into valueAsColumn values(0,'Carol','B');
mysql> insert into valueAsColumn values(0,'Sam','C');
mysql> insert into valueAsColumn values(1,'John','D');
mysql> insert into valueAsColumn values(1,'Carol','A');
mysql> insert into valueAsColumn values(1,'Carol','C');

使用select语句显示表中的所有记录。查询如下-

mysql> select *from valueAsColumn;

以下是输出-

+--------+-------------+-------------+
| UserId | UserColumn1 | UserColumn2 |
+--------+-------------+-------------+
|      0 | John        | A+          |
|      0 | Carol       | B           |
|      0 | Sam         | C           |
|      1 | John        | D           |
|      1 | Carol       | A           |
|      1 | Carol       | C           |
+--------+-------------+-------------+
6 rows in set (0.00 sec)

这是将列值设置为列名的查询-

mysql> select UserId,
   -> max(case when (UserColumn1='John') then UserColumn2 else NULL end) as 'John',
   -> max(case when (UserColumn1='Carol') then UserColumn2 else NULL end) as 'Carol',
   -> max(case when (UserColumn1='Sam') then UserColumn2 else NULL end) as 'Sam'
   -> from valueAsColumn
   -> group by UserId
   -> order by UserId;

以下是输出-

+--------+------+-------+------+
| UserId | John | Carol | Sam  |
+--------+------+-------+------+
|      0 | A+   | B     | C    |
|      1 | D    | C     | NULL |
+--------+------+-------+------+
2 rows in set (0.00 sec)