2013-12-23 81 views
0

我已經做了以下查詢,但是當我嘗試選擇多一列時,我沒有得到任何結果。我只是不知道如何選擇該列(if語句是有問題的)。MySQL選擇列,如果它存在

東西是sub_acc列中的cash_payment_detail表也可以是null。任何幫助都意味着很多。請注意,我仍在學習。

SELECT 
    LPAD(cash_payments_detail.`control_acc`,5,0) AS Control_Account, 
    CAccountDescription As Control_Account_Name, 
    LPAD(cash_payments_detail.`sub_acc`,4,0) AS Sub_Account, 
    **if (coasub.`SAccountNo` = cash_payments_detail.`sub_acc`, coasub.`SAccountDescription`," ") As Sub_Account_Name** 
FROM 
    coasub, coacontrol, `cash_payments_detail` cash_payments_detail INNER JOIN `cash_payments` cash_payments ON cash_payments_detail.`cpvno` = cash_payments.`cpvno` 
WHERE 
control_acc = coacontrol.`CAccountNo` 
+0

大膽(**)列不會在查詢中顯示。 – Roger

+0

哎呦抱歉,它的**,if語句 – user1361430

+0

1)你必須使用'OUTER JOIN'例如'LEFT JOIN' 2)不要混合使用逗號樣式和ANSI樣式'JOIN's – peterm

回答

0

你的問題是在連接你做,你要學會的加入以及寫這樣的查詢之前,您會注意到你一起寫不返回記錄時 cash_payment_detail.sub_acc爲空 左連接將返回空值;) 使用LEFT JOIN代替內加入 ... 嘗試此查詢:

SELECT 
cash_payments.cpvno AS Voucher_Number, date_format(cash_payments.vdate,'%d %M %Y') AS Voucher_Date, 
sec_users.name AS Entered_By, cash_payments.payto AS Payment_To, cash_payments.payref AS On_Account_Of, LPAD(cash_payments.branch,5,0) AS Cash_Control_Account, branches.cash_control_name AS Cash_Control_Name, 
branches.name AS Branch_Name, 
LPAD(cash_payments_detail.control_acc,5,0) AS Control_Account, CAccountDescription As Control_Account_Name, 
LPAD(cash_payments_detail.sub_acc,4,0) AS Sub_Account, if (SAccountNo = sub_acc, SAccountDescription," ") As Sub_Account_Name, 
cash_payments_detail.job_no AS Job, cash_payments_detail.narration AS Narration, cash_payments_detail.debit AS Debit 
FROM 
coasub, coacontrol, branches, sec_users, cash_payments_detail cash_payments_detail 
LEFT JOIN cash_payments cash_payments ON cash_payments_detail.cpvno = cash_payments.cpvno 
WHERE 
control_acc = coacontrol.CAccountNo AND cashcontrol = cash_payments.branch AND cash_payments.login = sec_users.login 
+0

感謝您的回覆。對此,我真的非常感激。我試了左連接,甚至完全刪除了連接,並使用where子句,但沒有運氣編輯:沒關係我想通了,混合了聯接。感謝幫助。 – user1361430

相關問題