'use the If else condition for selecting the column in 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.
Solution 1:[1]
I have a mysql query for multiple select field using if ... else statements or using case statement. This is described below.
MYSQL select using if statement
select IF('fieldname with condition','if true value','if false value') from table_name where 1;MYSQL select using multiple if else
select CASE WHEN fieldname1 = 'value1' THEN 'if true then give value' WHEN fieldname2 = 'value2' THEN 'if true then give value' THEN 'if true then give value' WHEN fieldname3 = 'value3' THEN 'if true then give value' THEN 'if true then give value' WHEN fieldname4 = 'value4' THEN 'if true then give value' THEN 'if true then give value' ELSE 'else all false then give default value' END as STATUS, from table_name where 1;
Try using these queries.
Solution 2:[2]
SELECT IF(t1.AccountNo IS NULL, t2.TempAccountNo, t2.AccountNo) AS Acc_common
FROM table1 t1
INNER JOIN table2 t2 ON t1.AccountNo = t2.AccountNo
This will help..
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris Frederick |
| Solution 2 | Prabhagaran |
