我想回显每月创建的发票总数。
下面的代码到目前为止可以正常工作,但是如果一个月内没有结果,则需要0。
$sql = "SELECT MONTH( invoice_date ) AS MONTH, SUM(`invoice`.`total`) as total
FROM `invoices`
WHERE YEAR(invoice_date) = '2019'
GROUP BY MONTH(invoice_date)";
$result = mysqli_query($con,$sql);
while($data = mysqli_fetch_array($result))
{
$total = $data['total'];
$month = $data['month'];
}
我想要的是这个
Jan 500
Feb 300
Mar 0
Apr 500
etc...
我得到的是这个
500年1月 2月300 500年4月
...因为在我的数据库中没有Mar的条目。
如果我每个月都循环执行一次查询,效果很好,但我知道我不应该这样使用,还有更好的方法!?
答案 0 :(得分:1)
使用UNION ALL
创建一个查询,该查询将所有月份数字1-12和LEFT JOIN返回到您的查询:
SELECT m.MONTH, COALESCE(t.total, 0)
FROM (
SELECT 1 AS MONTH UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL
SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
) AS m LEFT JOIN (
SELECT MONTH( invoice_date ) AS MONTH, SUM(`invoice`.`total`) as total
FROM `invoices`
WHERE YEAR(invoice_date) = '2019'
GROUP BY MONTH(invoice_date)
) AS t ON t.MONTH = m.MONTH