Ricerca nel sito web

Qual è più veloce, un'istruzione CASE di MySQL o un'istruzione if di PHP?


L'istruzione CASE di MySQL è più veloce rispetto all'istruzione if di PHP. L'istruzione if di PHP richiede troppo tempo perché carica i dati e quindi li elabora mentre l'istruzione CASE no.

Creiamo innanzitutto una tabella e aggiustiamo un esempio di istruzione CASE di MySQL:

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

Inserisci alcuni record nella tabella utilizzando il comando di inserimento:

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)

Visualizza tutti i record dalla tabella utilizzando l'istruzione select :

mysql> select *from DemoTable;

Ciò produrrà il seguente output:

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

Di seguito è riportata la query per l'istruzione CASE di MySQL:

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;

Ciò produrrà il seguente output:

+-------+-------------------------------------+
| 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)

Articoli correlati: