MySQL选择列(如果存在)

时间:2013-12-23 08:13:31

标签: mysql if-statement exists

我已经进行了以下查询,但是当我尝试再选择一个列时,我得不到任何结果。我只是想弄清楚如何选择该列(if语句是有问题的那个)。

问题是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`

1 个答案:

答案 0 :(得分:0)

你的问题在于你在编写此类查询之前必须学习连接的连接,并注意到您编写的连接在返回时没有返回记录 cash_payment_detail.sub_acc为空 左连接将返回空值;) 使用左连接代替内连接 ... 试试这个查询:

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