将列值设置为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)
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬