在MYSQL中查找两个数字之间的绝对差异的最佳方法是什么,以便我可以订购结果?以下情况适用,仅当numberA大于numberB时,但正如您所看到的情况并非总是如此。有一个好的方法可以用一个语句来做到这一点吗?
SELECT (numberA - numberB) AS spread
FROM table
ORDER BY spread DESC
|-------------------|
| numberA | numberB |
| 5.4 | 2.2 |
| 7.7 | 4.3 |
| 1 | 6.5 |
| 2.3 | 10.8 |
| 4.5 | 4.5 |
答案 0 :(得分:18)
就像that一样简单:
SELECT ABS(numberA - numberB) AS spread
FROM table
ORDER BY spread DESC
或者,如果你想要select the pair (numberA, numberB) in descending order of their difference:
SELECT numberA, numberB
FROM table
ORDER BY ABS(numberA - numberB) DESC
答案 1 :(得分:0)
MySQL具有ABS()功能:
select abs(numberA - numberB) as abs_diff
from your_table
ORDER BY abs_diff DESC