In PHP I'm doing a query to my database using MySQL. In my database I have the fotos_album
table and inside I have the name of the photo. I want to sort the table by the nome
field.
We imagine that the table has the following data:
id nome
1 corrida (1 de 140)
2 corrida (20 de 140)
3 corrida (5 de 140)
4 corrida (2 de 140)
The goal is for my order to look like this:
id nome
1 corrida (1 de 140)
4 corrida (2 de 140)
3 corrida (5 de 140)
2 corrida (20 de 140)
For this to happen it is not enough to use ORDER BY nome ASC
, so how can I make the sort order correct?
Edited: The name is entered by the user. If it inserts the name field as I wrote above, a simple sort does not work
I have tried the following, but it does not work correctly in all cases:
SELECT *
FROM fotos_album
WHERE id = '$id_noticia'
ORDER BY
SUBSTR(nome,
LEAST(
CASE WHEN LOCATE('0', nome)>0 THEN LOCATE('0', nome) ELSE LENGTH(nome) END,
CASE WHEN LOCATE('1', nome)>0 THEN LOCATE('1', nome) ELSE LENGTH(nome) END,
CASE WHEN LOCATE('2', nome)>0 THEN LOCATE('2', nome) ELSE LENGTH(nome) END,
CASE WHEN LOCATE('3', nome)>0 THEN LOCATE('3', nome) ELSE LENGTH(nome) END,
CASE WHEN LOCATE('4', nome)>0 THEN LOCATE('4', nome) ELSE LENGTH(nome) END,
CASE WHEN LOCATE('5', nome)>0 THEN LOCATE('5', nome) ELSE LENGTH(nome) END,
CASE WHEN LOCATE('6', nome)>0 THEN LOCATE('6', nome) ELSE LENGTH(nome) END,
CASE WHEN LOCATE('7', nome)>0 THEN LOCATE('7', nome) ELSE LENGTH(nome) END,
CASE WHEN LOCATE('8', nome)>0 THEN LOCATE('8', nome) ELSE LENGTH(nome) END,
CASE WHEN LOCATE('9', nome)>0 THEN LOCATE('9', nome) ELSE LENGTH(nome) END
)
) + 0