How to query the database for a between-value and sort by the nearest?
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
Is it possible to sort the re开发者_开发技巧sults within MySQL or do I have to sort them afterwards with PHP?
you should be able to add an order by clause like so:
ORDER BY ABS(150-field)
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.
精彩评论