📅  最后修改于: 2023-12-03 15:17:45.798000             🧑  作者: Mango
In MySQL, the IF
statement can be used to conditionally execute statements based on a certain condition. The IF ELSE
statement is used when we want to execute different sets of statements based on different conditions.
This guide will provide an in-depth explanation of the IF ELSE
statement in MySQL and demonstrate its usage with code examples.
The syntax of the IF ELSE
statement in MySQL is as follows:
IF condition THEN
-- Statements to execute if the condition is true
ELSE
-- Statements to execute if the condition is false
END IF;
The IF ELSE
statement starts with the IF
keyword, followed by a condition. If the condition is true, the statements inside the IF
block will be executed. If the condition is false, the statements inside the ELSE
block will be executed.
Let's consider an example where we have a table named employees
with columns id
, name
, and salary
. We want to categorize the employees as "Low Salary" or "High Salary" based on their salary. If the salary is less than 5000, they are considered as "Low Salary" employees, otherwise "High Salary" employees.
-- Create employees table
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2)
);
-- Insert sample data
INSERT INTO employees (id, name, salary)
VALUES (1, 'John Doe', 4500),
(2, 'Jane Smith', 6000),
(3, 'David Johnson', 3500),
(4, 'Emily Williams', 7500);
-- Categorize employees based on salary
SELECT id, name, salary,
IF(salary < 5000, 'Low Salary', 'High Salary') AS category
FROM employees;
In the above example, we first create the employees
table and insert some sample data. Then, we use the IF
statement in the SELECT
query to categorize the employees based on their salary. The IF
function returns the value based on the condition specified.
The IF ELSE
statement in MySQL allows us to execute different sets of statements based on conditions. It is a powerful tool for controlling the flow of execution in SQL queries. By properly utilizing the IF ELSE
statement, programmers can create more dynamic and efficient database queries.