【发布时间】:2018-03-13 16:09:51
【问题描述】:
我有这样的mysql表
| idx| name | year | month | value |
| 1 | foo | 2017 | 1 | bar1 |
| 2 | foo | 2017 | 2 | bar2 |
| 3 | foo | 2017 | 3 | bar3 |
| 4 | foo | 2017 | 4 | bar4 |
我想查询这样的网格表
| idy | name | year | month1 | month2 | month3 | month4 |
| 1 | foo | 2017 | bar1 | bar2 | bar3 | bar4 |
如何做到这一点,非常感谢
我的意思是查询一行到一行,我想像这样填充表格
<table>
<tr>
<th>id</th>
<th>name</th>
<th>year</th>
<th>month1</th>
<th>month2</th>
<th>month3</th>
<th>month4</th>
</tr>
<tr>
<td><?php echo $row[id]; ?></td>
<td><?php echo $row[name]; ?></td>
<td><?php echo $row[year]; ?></td>
<td><?php echo $row[month1]; ?></td>
<td><?php echo $row[month2]; ?></td>
<td><?php echo $row[month3]; ?></td>
<td><?php echo $row[month4]; ?></td>
</tr>
</table>
【问题讨论】:
-
您的查询在哪里?
-
like select * from table where name='foo' and year=2017 .....blablabla 我不知道该怎么做
-
这就是您需要的所有查询。
-
不,先生,我只想选择这样的表格
-
这种转换称为旋转,这个问题已经在 SO 上被问过并回答了好几次。这两个重复的主题解释了如何在 MySQL 中创建数据透视表。但是,在应用程序中进行旋转可能更有效(在这种特殊情况下是 php)。