mySQL从行创建列

时间:2017-07-12 12:43:47

标签: mysql sql mysqli

从这种表中:

| id | value1 | valueMax1  | value2 | valueMax2  | value3 | valueMax3  |
| 1  |  10    |  25        |  11    |  25        |  12    |  25        |
| 2  |  20    |  35        |  21    |  35        |  22    |  35        |

是否可以制作一个返回此选项的选项:

| id | in | value | valueMax |
| 1  | 1  |  10   |  25      |
| 1  | 2  |  11   |  25      |
| 1  | 3  |  12   |  25      |
| 1  | 4  |  13   |  35      |
| 2  | 1  |  20   |  35      |
| 2  | 2  |  21   |  35      |
| 2  | 3  |  22   |  35      |
| 2  | 4  |  23   |  35      |

到目前为止,我已尝试使用GROUP_CONCAT或SELECT内部的SELECT,但它不是我正在寻找的结果。根据评论,如果添加IN = 4,接下来将展示我想要发生的事情。

使用新数据:

| id | value1 | valueMax1  | value2 | valueMax2  | value3 | valueMax3  | value4 | valueMax4  |
| 1  |  10    |  25        |  11    |  25        |  12    |  25        |  13    |  35        |
| 2  |  20    |  35        |  21    |  35        |  22    |  35        |  23    |  35        |

选择结果:

!

注意:作为一个附加功能,无论如何实际得到这样的结果而不知道IN值的确切数量?因此,相同的查询将适用于具有2个有效值IN的表,以及具有5个有效值的表。

3 个答案:

答案 0 :(得分:1)

你可以这样做:

| id |  value    | valueMax   | 
| 1  |  10,11    |  25,25,25  | 
| 2  |  20,21    |  35,35,35  |

以这种方式:

SELECT id, GROUP_CONCAT(string SEPARATOR ' ') FROM table GROUP BY id;

How to use GROUP BY to concatenate strings in MySQL?

答案 1 :(得分:0)

解决方案是多重自我加入:

SELECT t1.id
      ,t1.value     AS value1
      ,t1.valueMax  AS valueMax1
      ,t2.value     AS value2
      ,t2.valueMax  AS valueMax2
      ,t3.value     AS value3
      ,t3.valueMax  AS valueMax3      
  FROM yourtable t1
  LEFT OUTER JOIN yourtable t2
    ON t1.id = t2.id
   AND t2.in = 2
  LEFT OUTER JOIN yourtable t3
    ON t1.id = t3.id    
   AND t2.in = 3
 WHERE t1.in = 1 

答案 2 :(得分:0)

您也可以使用Mysql Case来获得所需的结果

SELECT id, SUM((CASE WHEN `in` = 1 THEN value ELSE  0 END)) AS value1,
SUM((CASE WHEN `in` = 1 THEN valueMAX ELSE  0 END)) AS valueMAX1,
SUM((CASE WHEN `in` = 2 THEN value ELSE  0 END)) AS value2,
SUM((CASE WHEN `in` = 2 THEN valueMAX ELSE  0 END)) AS valueMAX2,
SUM((CASE WHEN `in` = 3 THEN value ELSE  0 END)) AS value3,
SUM((CASE WHEN `in` = 3 THEN valueMAX ELSE  0 END)) AS valueMAX3 FROM `table` group by id