我正在尝试选择在特定时期内完成的所有类别和交易。为此,我有这个查询:
SELECT
b.category, SUM(a.value) as 'total'
FROM
transactions a,
transactions_category b
WHERE a.type = 2
AND YEAR(a.date) = :year
AND MONTH(a.date) = :month
AND a.id_category = b.id
GROUP BY a.id_category
ORDER BY total DESC
这工作正常,但它只选择具有与之关联的任何事务的类别。例如,如果我有一个名为“Internet”的类别,并且在那个月没有与“Internet”相关的交易,那么它将不会显示在该列表上。
即使当月没有交易,我如何选择所有类别的交易总和?
预期的结果将是这样的:
category: 'Office', total: 240,00
category: 'Internet', total: 0,00
category: 'Food', total: 580,00
...
使用left
join并将所有过滤器从where
子句移动到on
clasue
SELECT
c.category, SUM(t.value) as 'total'
FROM transactions_category c
LEFT JOIN transactions t
ON t.id_category = c.id
AND t.type = 2
AND YEAR(t.date) = :year
AND MONTH(t.date) = :month
GROUP BY c.category
ORDER BY total DESC
这样,您将始终获得左表的所有行,即类别表