mysql case when
时间: 2023-09-05 14:14:06 浏览: 119
SQL case_when用法
MySQL CASE WHEN statement is a conditional statement that evaluates multiple conditions and returns a value based on the first condition that is true.
The basic syntax for the MySQL case when statement is as follows:
```
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
WHEN conditionN THEN resultN
ELSE default_result
END
```
Here is an example of how to use the MySQL case when statement:
```
SELECT first_name, last_name,
CASE
WHEN age < 18 THEN 'Minor'
WHEN age BETWEEN 18 AND 65 THEN 'Adult'
ELSE 'Senior'
END AS age_group
FROM customers;
```
In this example, we are selecting the first name, last name, and age group of customers from the customers table. We use the MySQL case when statement to evaluate the age of each customer and assign them to an age group based on their age. If the customer is under 18, they are assigned to the 'Minor' group, if they are between 18 and 65, they are assigned to the 'Adult' group, and if they are over 65, they are assigned to the 'Senior' group.
The resulting output would look something like this:
```
+------------+-----------+-----------+
| first_name | last_name | age_group |
+------------+-----------+-----------+
| John | Doe | Adult |
| Jane | Smith | Senior |
| Bob | Johnson | Minor |
| Sarah | Lee | Adult |
+------------+-----------+-----------+
```
阅读全文