I am having two tables like this.Both are separate tables
AccountNo User Name ---------------------------------- 1 U a 2 U b 3 U c
And another table contains the following structure
TempAccountNo Mycolumn AccountNo ------------------------------------------ 4 X 2341 5 Y 2 6 Z 2568
I need to select the AccountNo or TempAccountNo,Mycolumn From table II and the condition is
If (tableII.AccountNo not in table I) I need to choose `TempAccountNo from table II` else I need to choose `AccountNo from table II`
How can I achieve this.
Answer: MySQL IF() function can be used within a query, while the IF-ELSE conditional statement construct is supported to be used through FUNCTIONS or STORED PROCEDURES.
Solution 1. DECLARE @query VARCHAR(1000)=null; SET @query = 'ID'; IF((select phone1 from tablename where id = 1459) > 0) SET @query += ',phone1'; IF((select phone2 from tablename where id = 1459) > 0) SET @query += ',phone2'; .. .. .. IF (@query IS NOT NULL) exec('SELECT '+@query+' FROM tablename WHERE id = 1459');
The syntax for the IF-THEN-ELSE statement in MySQL is: IF condition1 THEN {... statements to execute when condition1 is TRUE...} [ ELSEIF condition2 THEN {...
To select a column that is also a keyword in MySQL, you need to use backticks around the column name. As you know select is a keyword in MySQL, consider column name as select when creating a new table.
SELECT IF( t1.AccountNo IS NULL, -- condition t2.TempAccountNo, -- true branch t2.AccountNo -- false branch ) AS optional_field FROM table2 t2 LEFT JOIN t1 ON t1.AccountNo = t2.AccountNo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With