如何找到两个数字MYSQL的绝对差异

时间:2022-01-12 04:30:00

What's the best way to find the absolute difference between two numbers in MYSQL so that I may order results? The below works, only if numberA is larger than numberB, but as you can see this is not always the case. Is there a good way to do this with one statement?

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

2 个解决方案

#1


14  

As simple as that:

就如此容易:

SELECT ABS(numberA - numberB) AS spread 
FROM table 
ORDER BY spread DESC

Or, if you want to select the pair (numberA, numberB) in descending order of their difference:

或者,如果要按差异的降序选择对(numberA,numberB):

SELECT numberA, numberB
FROM table 
ORDER BY ABS(numberA - numberB) DESC

#2


0  

MySQL has an ABS() function for that:

MySQL有一个ABS()函数:

select abs(numberA - numberB) as abs_diff
from your_table
ORDER BY abs_diff DESC

#1


14  

As simple as that:

就如此容易:

SELECT ABS(numberA - numberB) AS spread 
FROM table 
ORDER BY spread DESC

Or, if you want to select the pair (numberA, numberB) in descending order of their difference:

或者,如果要按差异的降序选择对(numberA,numberB):

SELECT numberA, numberB
FROM table 
ORDER BY ABS(numberA - numberB) DESC

#2


0  

MySQL has an ABS() function for that:

MySQL有一个ABS()函数:

select abs(numberA - numberB) as abs_diff
from your_table
ORDER BY abs_diff DESC