Ordine MySQL per campo utilizzando l'istruzione CASE
Per ordinare per campo, utilizzare l'istruzione CASE. Creiamo innanzitutto una tabella:
mysql> create table DemoTable(StudentId varchar(100));
Query OK, 0 rows affected (1.69 sec)
Inserisci alcuni record nella tabella utilizzando il comando di inserimento:
mysql> insert into DemoTable values('STU-980');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable values('STU-1029');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable values('STU-189');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('STU-890');
Query OK, 1 row affected (0.38 sec)
Visualizza tutti i record dalla tabella utilizzando l'istruzione select :
mysql> select *from DemoTable;
Ciò produrrà il seguente output:
+-----------+
| StudentId |
+-----------+
| STU-980 |
| STU-1029 |
| STU-189 |
| STU-890 |
+-----------+
4 rows in set (0.00 sec)
Di seguito è riportata la query su MySQL ordinata per campo:
mysql> select *from DemoTable
order by case WHEN StudentId = 'STU-890' THEN 1
WHEN StudentId = 'STU-1029' THEN 2
WHEN StudentId = 'STU-980' THEN 3
WHEN StudentId = 'STU-189' THEN 4
end;
Ciò produrrà il seguente output:
+-----------+
| StudentId |
+-----------+
| STU-890 |
| STU-1029 |
| STU-980 |
| STU-189 |
+-----------+
4 rows in set (0.08 sec)