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

mysqlmysqli database

要将列值设置为查询结果中的列名,您需要使用 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)
   -> );
Query OK, 0 rows affected (0.75 sec)

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

mysql> insert into valueAsColumn values(0,'John','A+');
Query OK, 1 row affected (0.18 sec)
mysql> insert into valueAsColumn values(0,'Carol','B');
Query OK, 1 row affected (0.17 sec)
mysql> insert into valueAsColumn values(0,'Sam','C');
Query OK, 1 row affected (0.17 sec)
mysql> insert into valueAsColumn values(1,'John','D');
Query OK, 1 row affected (0.20 sec)
mysql> insert into valueAsColumn values(1,'Carol','A');
Query OK, 1 row affected (0.20 sec)
mysql> insert into valueAsColumn values(1,'Carol','C');
Query OK, 1 row affected (0.15 sec)

使用 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)

相关文章