列中的COUNT值和生成结果表mysql

时间:2014-08-08 13:23:11

标签: php mysql

为了这个问题的序言 - 我知道我错过了一些非常明显的东西,但现在是星期五下午!

我尝试将COUNT次转换为某些值出现在同一列中并生成结果表的次数。

到目前为止,这是我的代码:

MYSQL

SELECT COUNT(order_status) as printed
FROM orders WHERE order_status = 'Printed Order'

UNION

SELECT COUNT(order_status) as charged
FROM orders WHERE order_status = 'Charged Order'

UNION

SELECT COUNT(order_status) as exchanged
FROM orders WHERE order_status = 'Exchanged Order'

UNION

SELECT COUNT(order_status) as refunded
FROM orders WHERE order_status = 'Refunded Order'

UNION

SELECT COUNT(order_status) as cancelled
FROM orders WHERE order_status = 'Cancelled Order'
GROUP BY order_status

以上查询的结果

printed
-------
224
19190
593
2618
2899

代码生成正确的数字,但是,我希望结果如下:

期望的结果

printed - 224
charged - 19190
exchanged - 593
refunded - 2618
cancelled -2899

这样我可以通过关联数组调用轻松引用它们,即$order_status['printed']

任何帮助都会很棒。

3 个答案:

答案 0 :(得分:3)

添加指定类型的列。最简单的方法是使用group by

select order_status, count(*)
from orders o
group by order_status;

答案 1 :(得分:0)

如果您使用PDO,请将获取模式设置为默认情况下创建关联数组:

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

答案 2 :(得分:-1)

尝试:

SELECT order_status, COUNT(order_status) as printed
FROM orders WHERE order_status = 'Printed Order'
GROUP BY order_status