[英]How to count different values in a same column in mysql?
i have a table like this 我有这样的桌子
id(pk)|product_id(fk)|serial(varchar)|status(varchar)
1 | 2 | e098 | sold
2 | 2 | e008 | faulty
what i need to extract is: 我需要提取的是:
array(faulty=>1,sold=>1)
ii can do it with a complex query, is there any SIMPLE query which can help? ii可以通过复杂的查询来做到这一点,是否有任何简单查询可以提供帮助? i tried this:
SELECT COUNT(id) as product_details.status FROM product_details WHERE product_id=2 GROUP BY status
which didn't work. 我尝试了此操作:
SELECT COUNT(id) as product_details.status FROM product_details WHERE product_id=2 GROUP BY status
,其中SELECT COUNT(id) as product_details.status FROM product_details WHERE product_id=2 GROUP BY status
无效。
(ab)Use mysql's auto-typecasting: (ab)使用mysql的自动类型转换:
SELECT SUM(status='sold') AS sold, SUM(status='faulty') AS faulty
FROM ...
the boolean result of status='sold'
will be typecast to integer 0/1 and then summed up. status='sold'
的布尔结果将类型转换为整数0/1,然后求和。
The other option is just to do a regular query and then do the pivoting in client-side code: 另一种选择是执行常规查询,然后在客户端代码中进行透视:
SELECT id, status, COUNT(status) AS count
FROM ...
GROUP BY id, status
and then 接着
while(... fetch ...) {
$results[$row['id']][$row['status']] = $row['count'];
}
您还需要查询状态。
SELECT status, COUNT(id) as count FROM product_details WHERE product_id=2 GROUP BY status
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.