@Stephen:您的解决方案在issue_items上为items上的每一行发出子查询,不是吗?
我认为这可能是一个更便宜的解决方案:
SELECT items.month,
items.amount as Rreceived,
issued_items.amount as Issued,
items.currency
FROM (
SELECT date_format(items.date, '%M %Y') as month,
COALESCE(SUM(items.amount), 0) as amount,
items.currency
FROM items
GROUP BY date_format(items.date, '%Y-%m')
) items
LEFT JOIN (
SELECT date_format(issued_items.date, '%M %Y') as month,
COALESCE(SUM(issued_items.amount), 0) as amount,
issued_items.currency
FROM issued_items
GROUP BY date_format(issued_items.date, '%Y-%m')
)
issued_items
ON items.month=issued_items.month
AND items.currency=issued_items.currency
CHANGE
IFNULL 可以解决您的问题(如 Oracle 中的 NVL)
SELECT items.month,
ifnull(items.amount,0) as Rreceived,
ifnull(issued_items.amount,0) as Issued,
items.currency
FROM (
SELECT date_format(items.date, '%M %Y') as month,
COALESCE(SUM(items.amount), 0) as amount,
items.currency
FROM items
GROUP BY date_format(items.date, '%Y-%m')
) items
LEFT JOIN (
SELECT date_format(issued_items.date, '%M %Y') as month,
COALESCE(SUM(issued_items.amount), 0) as amount,
issued_items.currency
FROM issued_items
GROUP BY date_format(issued_items.date, '%Y-%m')
)
issued_items
ON items.month=issued_items.month
AND items.currency=issued_items.currency