mysql with case
时间: 2023-10-13 07:23:30 浏览: 93
`CASE` is a conditional statement in MySQL that allows you to evaluate a series of conditions and return a value based on the first condition that is true. You can use `CASE` in conjunction with SQL statements like `SELECT`, `UPDATE`, and `DELETE`.
Here is an example of using `CASE` in a `SELECT` statement:
```
SELECT order_id,
CASE
WHEN order_total >= 1000 THEN 'High'
WHEN order_total >= 500 THEN 'Medium'
ELSE 'Low'
END AS order_priority
FROM orders;
```
In this example, we are selecting the `order_id` column from the `orders` table and creating a new column called `order_priority`. The value of `order_priority` is determined by the `CASE` statement. If `order_total` is greater than or equal to 1000, then `order_priority` is set to 'High'. If `order_total` is greater than or equal to 500, then `order_priority` is set to 'Medium'. Otherwise, `order_priority` is set to 'Low'.
You can also use `CASE` in conjunction with other SQL statements, such as `UPDATE`. Here is an example of updating a table using `CASE`:
```
UPDATE employees
SET salary = CASE
WHEN department = 'Sales' THEN salary * 1.1
WHEN department = 'Marketing' THEN salary * 1.2
ELSE salary
END;
```
In this example, we are updating the `salary` column in the `employees` table. The new value of `salary` is determined by the `CASE` statement. If the `department` is 'Sales', then `salary` is multiplied by 1.1. If the `department` is 'Marketing', then `salary` is multiplied by 1.2. Otherwise, `salary` remains the same.
Overall, `CASE` is a useful tool in MySQL for creating conditional statements and controlling the flow of your SQL queries.
阅读全文