MySQL CASE 语句和 PHP if 语句哪个更快?

mysqlmysqli database

与 PHP if 语句相比,MySQL CASE 语句更快。PHP if 语句需要花费太多时间,因为它会加载数据然后进行处理,而 CASE 语句则不会。

让我们首先创建一个表并围绕 MySQL CASE 语句的示例进行操作 −

mysql> create table DemoTable (Value int);
Query OK, 0 rows affected (0.70 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(500);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(1000);
Query OK, 1 row affected (0.13 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+-------+
| Value |
+-------+
| 100   |
| 500   |
| 1000  |
+-------+
3 rows in set (0.00 sec)

以下是 MySQL CASE 语句的查询−

mysql> select Value, case when Value > 500 THEN "It is greater than or equal to 1000"
   else
   "It is lower than 1000"
   end as comparison from DemoTable;

这将产生以下输出 −

+-------+-------------------------------------+
| Value | comparison                          |
+-------+-------------------------------------+
|   100 | It is lower than 1000               |
|   500 | It is lower than 1000               |
| 1000 | It is greater than or equal to 1000  |
+-------+-------------------------------------+
3 rows in set (0.00 sec)

相关文章