MySQL一次查询多次计数

MySQL multiple count by one query

我试着统计这个月卖出了多少,然后得到一个数组。

$q = SELECT COUNT(id) AS January FROM tableName WHERE status='sold' AND month = '1'
UNION 
SELECT COUNT(id) AS February FROM tableName WHERE status='sold' AND month = '2'

$row = mysqli_fetch_array(mysqli_query($connection, $q));

print_r($row);

UNION 不起作用,当我尝试 print_r(数组)时,我得到结果

[Jenuary] => 200

如何在两个月获得一个阵列?

我要结果:

[January] => 200,
[February] => 221

我想你想要条件聚合:

select sum(month = 1) as january, sum(month = 2) as february
from tablename
where status = 'sold' and month in (1, 2)

这只生成一行,有两列称为 januaryfebruary,每列包含该月的行数。

或者您希望每月一行。在这种情况下,您可以使用简单的聚合:

select month, count(*) cnt
from tablename
where status = 'sold' and month in (1, 2)
group by month

您可以尝试此查询以获得您想要的准确结果。

select MONTHNAME(STR_TO_DATE(month, '%m')) as month, count(*) cnt
from tablename
where status = 'sold'
group by month

仅限特定月份

 select MONTHNAME(STR_TO_DATE(month, '%m')) as month, count(*) cnt
    from tablename
    where status = 'sold' and month in(1, 2)
    group by month