开发者

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

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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜