1

I Need to filter the query that have some conditional column as below:

 SELECT
     `c`.`fullname` AS `fullname`,
     IFNULL(`c`.`new_ic`,`c`.`old_ic`) AS `Ic`,
     `bla`.`loan_no` AS `Loan_No`,
     `bla`.`total_loan_amt` AS `Total_Loan_Amt`,
     `bla`.`monthly_installment` AS `Month_Inst_Amt`,
     `bla`.`disb_date` AS `disb_date` FROM (`customers` `c`
 JOIN `basic_loan_application` `bla`
    ON ((`bla`.`customer_uid` = `c`.`customer_uid`))) 
 WHERE Ic LIKE '%800%' ORDER BY `bla`.`Basic_Loan_Application_Id` DESC LIMIT 0, 10

But I cannot Use the Ic Field and return error as decribed below:

 Unknown column 'Ic' in 'where clause' 

I want try to avoid nested select if possible.

Is there another solution for this problem?

2

In the where clause, trade the Ic alias with IFNULL(c.new_ic,c.old_ic).

 SELECT
     `c`.`fullname` AS `fullname`,
     IFNULL(`c`.`new_ic`,`c`.`old_ic`) AS `Ic`,
     `bla`.`loan_no` AS `Loan_No`,
     `bla`.`total_loan_amt` AS `Total_Loan_Amt`,
     `bla`.`monthly_installment` AS `Month_Inst_Amt`,
     `bla`.`disb_date` AS `disb_date` FROM (`customers` `c`
 JOIN `basic_loan_application` `bla`
    ON ((`bla`.`customer_uid` = `c`.`customer_uid`))) 
 WHERE IFNULL(`c`.`new_ic`,`c`.`old_ic`) LIKE '%800%' ORDER BY `bla`.`Basic_Loan_Application_Id` DESC LIMIT 0, 1

This happen because the query execution order. In MySQL queries are parsed in this order:

1- FROM clause
2- WHERE clause
3- GROUP BY clause
4- HAVING clause
5- SELECT clause
6- ORDER BY clause 

Which means that queries is not executed the way we write them. So, the Ic alias is not defined in the moment of WHERE clause is executed.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.