为空列选择MySQL Month()

时间:2014-11-15 07:49:21

标签: mysql join left-join

有问题要问。当我使用左连接时,即使某个行的空值为空,我如何列出我的左表以显示数据?

继承我的疑问:

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个月的交易。

帮助??请??任何想法怎么??

1 个答案:

答案 0 :(得分: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`;