MySQL CASE 语句或者 PHP if 语句,哪个更快?
MySQL CASE 语句比 PHP if 语句更快。PHP if 语句需要花费较长时间,因为它加载数据而且随后才进行处理,而 CASE 语句却不如此。
让我们首先创建一个表并根据 MySQL CASE 语句举例说明 −
mysql> create table DemoTable (Value int); Query OK, 0 rows affected (0.70 sec)
使用插入命令向表中插入一些记录 −
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)
广告