表结构:
reference|transaction|member|summary|amount|action_by|created_at(unix timestamp)
我当前的 SQL 是:
select COALESCE(sum(`amount`) , 0) as `amount` , `transaction`
from `transactions`
where
`transaction` IN ('payment', 'deposit', 'withdraw') and
`created_at` >= unix_timestamp(DATE_SUB(NOW(), INTERVAL 15 DAY))
group by transaction
假设没有找到付款记录。
我仍然想得到它的结果。
目前的结果是:
100 | deposit
200 | withdraw
我需要的结果是:
100 | deposit
200 | withdraw
0 | payment
我尝试了几种方法,但无法产生预期的结果。 请帮助,我是 sql 的初学者。提前致谢。
最佳答案
您需要有一个单独的表,其中包含每个唯一的 transaction
值。这可以使用单独的表来完成,也可以使用如下派生表:
SELECT COALESCE(sum(`amount`),0) as amount, der.transaction_type
FROM (SELECT 'payment' as transaction_type
UNION SELECT 'deposit'
UNION SELECT 'withdraw') der
LEFT JOIN `transactions` t on t.transaction=der.transaction_type AND `transaction` AND `created_at` >= unix_timestamp(DATE_SUB(NOW(), INTERVAL 15 DAY))
group by der.transaction_type
这将被显示,但如果您的表中没有很多行,那么它应该没什么大不了的。如果您在列上有专用表和索引,它会执行得更好
关于php - MySQL : show 0 and transaction type when no result found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39949610/