MySQL-IF控制流函数

时间:2020-02-23 14:41:02  来源:igfitidea点击:

在本教程中,我们将学习MySQL中的IF控制流函数。

IF函数

我们使用IF函数检查给定条件,然后根据匹配返回一些值。

IF语法

IF (condition, result_for_true, result_for_false)

如果满足条件,则返回result_for_true。
否则返回result_for_false

在本教程中,我们将使用orders表。

表:订单

mysql> SELECT * FROM orders;
+---------+------------+--------+-------------+---------------------+---------------------+
| orderid | employeeid | amount | orderstatus | lastmodified        | created             |
+---------+------------+--------+-------------+---------------------+---------------------+
|       1 | e03        |  15.00 | OPEN        | 2016-01-02 03:04:05 | 2016-01-02 03:04:05 |
|       2 | e01        |  25.50 | OPEN        | 2016-01-04 03:04:03 | 2016-01-04 03:04:03 |
|       3 | e05        | 100.70 | CLOSED      | 2016-02-02 03:03:04 | 2016-02-02 03:03:04 |
|       4 | e02        |  22.18 | OPEN        | 2016-01-02 03:04:05 | 2016-01-02 03:04:05 |
|       5 | e04        |   9.50 | CANCELLED   | 2016-01-04 03:04:03 | 2016-01-04 03:04:03 |
|       6 | e04        |  99.99 | OPEN        | 2016-02-02 03:03:04 | 2016-02-02 03:03:04 |
+---------+------------+--------+-------------+---------------------+---------------------+
6 rows in set (0.00 sec)

例子1

在下面的示例中,我们将检查金额是"大于15"还是"小于或者等于15"。

mysql> SELECT 
    o.orderid,
    IF(o.amount > 15,
        'Greater than 15',
        'Less than or Equal to 15') AS result
FROM
    orders o;

+---------+--------------------------+
| orderid | result                   |
+---------+--------------------------+
|       1 | Less than or Equal to 15 |
|       2 | Greater than 15          |
|       3 | Greater than 15          |
|       4 | Greater than 15          |
|       5 | Less than or Equal to 15 |
|       6 | Greater than 15          |
+---------+--------------------------+
6 rows in set (0.00 sec)

例子2

在下面的示例中,我们将添加另一个IF函数,以检查金额是"大于15"还是"小于15"或者"等于15"。

mysql> SELECT 
    o.orderid,
    IF(o.amount > 15,
        'Greater than 15',
        IF(o.amount < 15,
            'Less than 15',
            'Equal to 15')) AS result
FROM
    orders o;

+---------+-----------------+
| orderid | result          |
+---------+-----------------+
|       1 | Equal to 15     |
|       2 | Greater than 15 |
|       3 | Greater than 15 |
|       4 | Greater than 15 |
|       5 | Less than 15    |
|       6 | Greater than 15 |
+---------+-----------------+
6 rows in set (0.00 sec)