Case statement in MySQL

前端 未结 6 1082
旧时难觅i
旧时难觅i 2020-11-29 00:54

I have a database table called \'tbl_transaction\' with the following definition:

id INT(11) Primary Key
action_type ENUM(\'Expense\', \'Inc         


        
6条回答
  •  暖寄归人
    2020-11-29 01:17

    Yes, something like this:

    SELECT
        id,
        action_heading,
        CASE
            WHEN action_type = 'Income' THEN action_amount
            ELSE NULL
        END AS income_amt,
        CASE
            WHEN action_type = 'Expense' THEN action_amount
            ELSE NULL
        END AS expense_amt
    
    FROM tbl_transaction;
    

    As other answers have pointed out, MySQL also has the IF() function to do this using less verbose syntax. I generally try to avoid this because it is a MySQL-specific extension to SQL that isn't generally supported elsewhere. CASE is standard SQL and is much more portable across different database engines, and I prefer to write portable queries as much as possible, only using engine-specific extensions when the portable alternative is considerably slower or less convenient.

提交回复
热议问题