Question

I'm searching a value in my MySQL-Database and want to sort the results by the nearest items.

Example:

I search for a value of 150, within my Query I now do the following:

SELECT * FROM table WHERE field BETWEEN 100 AND 200
The 100 and the 200 are calculated before by an easy addition and substraction. But now my results are messed up, because it gives me the results back like they were saved to the database.

Is it possible to sort the results within MySQL or do I have to sort them afterwards with PHP?

Was it helpful?

Solution

SELECT * 
FROM table 
WHERE field BETWEEN 100 AND 200
ORDER BY field

or did you want something like

SELECT * 
FROM table 
WHERE field BETWEEN 100 AND 200
ORDER BY ABS(150-field)

?

Anyway, there are interactive online SQL tutorials which should help you jump start your SQL skills.

OTHER TIPS

you should be able to add an order by clause like so:

ORDER BY ABS(150-field)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top