如何在 MySQL 中查找两个数字之间的绝对差?

mysqlmysqli database

要获取 MySQL 中两个数字之间的差,我们首先创建一个演示表

mysql> create table findDifferenceDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FirstNumber float,
   -> SecondNumber float
   -> );
Query OK, 0 rows affected (0.60 sec)

使用 insert 命令在表中插入一些记录。 查询语句如下 −

mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(4.2,2.3);
Query OK, 1 row affected (0.20 sec)
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(23.4,5.6);
Query OK, 1 row affected (0.14 sec)
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(5.8,34.56);
Query OK, 1 row affected (0.16 sec)
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(7.8,7.2);
Query OK, 1 row affected (0.16 sec)
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(12.8,10.2);
Query OK, 1 row affected (0.13 sec)

使用 select 语句显示表中的所有记录。查询如下 −

mysql> select *from findDifferenceDemo;

以下是输出 −

+----+-------------+--------------+
| Id | FirstNumber | SecondNumber |
+----+-------------+--------------+
| 1  | 4.2         |          2.3 |
| 2  | 23.4        |          5.6 |
| 3  | 5.8         |        34.56 |
| 4  | 7.8         |          7.2 |
| 5  | 12.8        |         10.2 |
+----+-------------+--------------+
5 rows in set (0.00 sec)

以下是在 MySQL 中查找两个数字之间的绝对差的查询

mysql> SELECT ABS(FirstNumber - secondNumber) AS diff
   -> from findDifferenceDemo
   -> order by diff desc;

以下是输出 −

+--------------------+
| diff               |
+--------------------+
| 28.760001182556152 |
| 17.799999713897705 |
| 2.6000003814697266 |
| 1.8999998569488525 |
| 0.6000003814697266 |
+--------------------+
5 rows in set (0.00 sec)

相关文章