MySQL-- if()函数 简单明了
MySQL的IF()函数是一个流程控制结构,它允许你根据某种条件进行判断,如果该条件成立(真/YES),那么就会返回一个值,如果不成立(假/NO),则会返回另一个值。
以下是一些使用MySQL IF()函数的示例:
- 简单的条件判断:
SELECT IF(1>2, 'YES', 'NO'); // 输出: NO
SELECT IF(1<2, 'YES', 'NO'); // 输出: YES
- 用于选择性的列值赋值:
CREATE TABLE Employees (
ID INT,
Name VARCHAR(100),
Salary INT
);
INSERT INTO Employees (ID, Name, Salary) VALUES (1, 'John', 2000);
INSERT INTO Employees (ID, Name, Salary) VALUES (2, 'Mary', 2500);
INSERT INTO Employees (ID, Name, Salary) VALUES (3, 'Sam', 2200);
INSERT INTO Employees (ID, Name, Salary) VALUES (4, 'Alice', 2300);
SELECT ID, Name, IF(Salary > 2300, 'High', 'Low') AS Salary_Level FROM Employees;
- 用于选择性的表连接:
CREATE TABLE Customers (
ID INT,
Name VARCHAR(100),
City VARCHAR(100)
);
INSERT INTO Customers (ID, Name, City) VALUES (1, 'John', 'New York');
INSERT INTO Customers (ID, Name, City) VALUES (2, 'Mary', 'Los Angeles');
INSERT INTO Customers (ID, Name, City) VALUES (3, 'Sam', 'Chicago');
INSERT INTO Customers (ID, Name, City) VALUES (4, 'Alice', 'Miami');
SELECT
Customers.ID,
Customers.Name,
IF(Customers.City = 'New York', 'NY', IF(Customers.City = 'Los Angeles', 'LA', 'Other')) AS Region
FROM
Customers;
- 用于选择性的列值查询:
SELECT
ID,
IF(Salary > 2300, 'High', 'Low') AS Salary_Level,
IF(Salary > 2300, Salary, NULL) AS Salary_High,
IF(Salary <= 2300, Salary, NULL) AS Salary_Low
FROM
Employees;
以上就是MySQL IF()函数的一些基本用法,希望对您有所帮助。
评论已关闭