2012-09-04 79 views
0

我需要獲取所有期間和當月的付款金額。有兩個表:類別和交易。加入select時的where子句

交易:

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` = '-' 

我需要加入前檢查子句中選擇,因爲minus_month的總和畢竟日期正在變爲空。 幫助PLZ

+3

提供表的模式。 – Ruwantha

回答

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 
+0

是的,我的英語不好,所以我會嘗試再次解釋我的問題。 Where子句不能用於'內部連接'。所有條件只能在選擇之後使用,當我需要在加入之前選擇條件 – user1645633