2014-11-15 74 views
0

有問題要問。當我使用左連接時,即使某行有空值時,我如何列出所有左表以顯示數據?選擇MySQL月份()爲空列

繼承人我查詢:

SELECT *, SUM(transactions.debit_credit) current_spending 
FROM (`budget`) LEFT JOIN `categories` ON `budget`.`category`=`categories`.`idcategory` 
LEFT JOIN `user_category` ON `budget`.`category`=`user_category`.`idcategory` 
LEFT JOIN `category_transaction` ON `budget`.`category`=`category_transaction`.`idcategory` 
LEFT JOIN `transactions` ON `category_transaction`.`idtransaction`=`transactions`.`idtransaction` 
WHERE `user_category`.`iduser` = '1' 
AND MONTH(transactions.transaction_date) = '11' 
GROUP BY `budget`.`idbudget`; 

當我刪除AND MONTH(transactions.transaction_date) = '11'的查詢工作正常接受它顯示的所有數據,而不只是1個月交易。

幫助??請??任何想法如何?

+0

注意transaction.transaction_date在TIMESTAMP數據類型 – kamudrikah

回答

0

您的where子句將您的left join轉換爲inner join,因爲您在連接表的條件下過濾數據。

而是把該條件的on子句中你加入

SELECT *, SUM(transactions.debit_credit) current_spending 
FROM (`budget`) 
LEFT JOIN `categories` ON `budget`.`category`=`categories`.`idcategory` 
LEFT JOIN `user_category` ON `budget`.`category`=`user_category`.`idcategory` 
         AND `user_category`.`iduser` = '1' 
LEFT JOIN `category_transaction` ON `budget`.`category`=`category_transaction`.`idcategory` 
LEFT JOIN `transactions` ON `category_transaction`.`idtransaction`=`transactions`.`idtransaction` 
         AND MONTH(transactions.transaction_date) = '11' 
GROUP BY `budget`.`idbudget`; 
+0

感謝您的幫助。我在select子句中添加了IFNULL()以獲得我的結果。 – kamudrikah