douhui8163 2012-11-12 01:37
浏览 15
已采纳

将mysql行转换为列

I have a table that has a status column, the status is a number between 1-8.

I can use the query

SELECT status, COUNT(id) AS total 
FROM cart_orders 
GROUP BY status;

To get a result that looks like:

status | total
1      | 10
2      | 15
3      | 8
4      | 51
5      | 65 
...

But that means every time I need the data I have to do:

$status = array(1 => null, 2 => null, 3 => null, 4 => null, 
                5 => null, 6 => null, 7 => null, 8 => null);

foreach($rows as $row){
    $status[$row['status']] = $row['total'];
}

Which, while not a lot of code I would like to avoid having to do that,

What I want is to modify the query so I end up with a single row that looks like:

1  | 2  | 3  | 4  | 5   
10 | 15 | 8  | 51 | 65 ...

so I can just go e.g. $row['4']

The only what I can think of to do this would be to have each column as a subquery, which I would rather use the code than have 8 sub-queries. The other option is to join the table on itself 7 times, but that is assumedly also not ideal?

How else could I do this?

  • 写回答

2条回答 默认 最新

  • dtcrw26206 2012-11-12 01:44
    关注

    What you are asking to do is called a "pivot query," which MySQL unfortunately does not support natively. What you must do is specify each row individually, as in:

    SELECT
       SUM(IF (status = 1, total, 0)) AS '1'
       ...
    

    ..but this is very verbose -- especially if you have a lot of columns. I think your PHP is a little more verbose than it needs to be too in that you don't need to declare the array ahead of time.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)