加入select时的where子句

时间:2012-09-04 09:03:12

标签: mysql join

我需要获得所有期间和当月的付款金额。有两个表:类别和交易。

交易:

id  int(11)                         
category    varchar(32)                          
dttm_added  datetime                    
minus   float               
minus_currency  varchar(32)

类:

id  int(11)                 
key varchar(32)                          
name    varchar(50)                          
type    varchar(1)

这是我的问题:

select  `key`, `id`, `name`, minus_month,month_cur
                                from `categories` as ct

                                left join (
                                select  `category` as tr_ct_m, date_format(`dttm_trans`, '%Y%m') as dat, sum(`minus`) as minus_month, `minus_currency` as month_cur from `transactions`  where dat = date_format(now(), '%Y%m')
                                ) as tr_m on tr_m.tr_ct_m = ct.key 
                                where `type` = '-'

我需要在加入之前检查select中的子句,因为在minus_month之后所有日期都变为Null。 帮助PLZ

1 个答案:

答案 0 :(得分:0)

不确定我是否理解正确,请在下面尝试:

select  `ct`.`key`, `ct`.`id`, `ct`.`name`, tr_m.minus_month,tr_m.month_cur from 
 ( select *   from `categories` where `type` = '-') as ct
left join 
 ( select  `category` as tr_ct_m, date_format(`dttm_trans`, '%Y%m') as dat, 
     sum(`minus`) as minus_month, `minus_currency` as month_cur from `transactions`  
     where dat = date_format(now(), '%Y%m')
 ) as tr_m on tr_m.tr_ct_m = ct.key