开发者

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 t开发者_Python百科able II`

else
  I need to choose `AccountNo from table II`

How can I achieve this.


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


I have a mysql query for multiple select field using if ... else statements or using case statement. This is described below.

  1. MYSQL select using if statement

    select IF('fieldname with condition','if true value','if false value') from table_name where 1;
    
  2. 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.


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..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜