Vediamo come effettuare il sort di un campo varchar come fosse un int usando mysql
Senza il fix si presenta uno scenario di questo tipo:
mysql> SELECT column FROM table_name ORDER BY column; column ====== 100 1000 10000 200 2000 20000 ...
Come vedete il sorting numerico non funziona correttamente con un campo varchar mysql.
Per fortuna il fix è relativamente semplice, di fatto aggiungo un +0 al campo di sorting in questo modo lo rendo un coefficente matematico e il sorting avviene correttamente:
mysql> SELECT column FROM table_name ORDER BY column+0; column ====== 100 200 1000 2000 10000 20000 ...
Et voilà! Questo articolo ti è servito? Scrivi nei commenti 😀
Image credits “php” disponibile @Shutterstock