我有一个表具有状态列,状态是1-8之间的数字。将mysql行转为列
我可以使用查询
SELECT status, COUNT(id) AS total
FROM cart_orders
GROUP BY status;
为了得到一个结果,看起来像:
status | total
1 | 10
2 | 15
3 | 8
4 | 51
5 | 65
...
但是,这意味着每一个我所需要的数据时,我必须做的:
$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'];
}
其中,虽然不是很多代码,我想避免必须这样做,
我要的是修改查询,所以我结束了一个单排,看起来像:
1 | 2 | 3 | 4 | 5
10 | 15 | 8 | 51 | 65 ...
这样我就可以去如$row['4']
我能想到的唯一的做法是将每列作为子查询,我宁愿使用代码而不是8个子查询。另一种选择是将自己的桌子连接7次,但这样做的效果并不理想?
我该怎么办?
http://www.artfulsoftware.com/infotree/queries.php#78 – 2012-11-12 01:39:42
啊,当然!这工作'COUNT(IF(STATUS = 1,id,NULL))AS s1, COUNT(IF(STATUS = 2,id,NULL))AS s2' – Hailwood
@Hailwood更好地使用'preparedStatement'。如果你有100种类型的身份呢?那么你的查询将会很长:D在我的答案下面看如何创建准备状态。 –