Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use the If else condition for selecting the column in mysql?

Tags:

mysql

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.

like image 218
svk Avatar asked Jan 14 '11 07:01

svk


People also ask

Can we use if statement in select query in MySQL?

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.

How do I select a column based on condition?

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');

How do I use if else in MySQL?

The syntax for the IF-THEN-ELSE statement in MySQL is: IF condition1 THEN {... statements to execute when condition1 is TRUE...} [ ELSEIF condition2 THEN {...

How do I select a column in MySQL?

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.


1 Answers

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 
like image 50
zerkms Avatar answered Oct 13 '22 20:10

zerkms