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

最佳答案

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

09-25 16:42