The CASE statement is used to return different values based on conditions. Its syntax is: CASE WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2 ELSE default_result END. It can be used to: define conditions, specify results, and provide default results. Other uses include value conversion, checking for NULL values, and selecting the largest or smallest value.
Usage of CASE in MySQL
The CASE statement is used in MySQL to return different values based on specified conditions. . Its syntax is as follows:
<code class="sql">CASE WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2 ELSE default_result END</code>
How to use the CASE statement?
Example:
Suppose there is a table named customers
with the following columns:
customer_id
: Customer IDcustomer_type
: Customer type (such as Standard, Premium) discount
: According to the customer Discounts provided by typeTo calculate discounts based on customer types, you can use the CASE statement:
<code class="sql">SELECT customer_id, CASE WHEN customer_type = 'Standard' THEN 0.1 WHEN customer_type = 'Premium' THEN 0.2 ELSE 0 END AS discount FROM customers;</code>
Other usage:
The CASE statement also Can be used for:
Note:
The above is the detailed content of How to use case in mysql. For more information, please follow other related articles on the PHP Chinese website!