mysqlmysql-select-db

how to selected data based on several conditions mysql


i have a table called my_table like this

+------------+--------+--------+
|  product   | type_1 | type_2 |
+------------+--------+--------+
| Banana     | A1     | B1     |
| Banana     | B1     | B2     |
| Watermelon | A      | B3     |
| Orange     | B      | B4     |
+------------+--------+--------+

so i want to make query IF the product banana, then it returns type_2, and the other product return type_1

so the expected results is just like this

+------------+------+
|  product   | type |
+------------+------+
| Banana     | B1   |  
| Banana     | B2   |  
| Watermelon | A    |  
| Orange     | B    | 
+------------+------+

Solution

  • You can use CASE to select the column you want.

    SELECT product, (CASE produt
                         WHEN 'Banana' THEN type_2
                         ELSE type_1
                     END) as type
    
    FROM my_table