如何在 MySQL 中返回一個值最接近使用者定義變數值的表記錄?


我們首先建立一個表 −

mysql> create table DemoTable
(
   CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ProductAmount int
);
Query OK, 0 rows affected (0.61 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable(ProductAmount) values(5000);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(ProductAmount) values(6000);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable(ProductAmount) values(7000);
Query OK, 1 row affected (0.26 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

這將生成以下輸出 −

+------------+---------------+
| CustomerId | ProductAmount |
+------------+---------------+
|          1 |          5000 |
|          2 |          6000 |
|          3 |          7000 |
+------------+---------------+
3 rows in set (0.00 sec)

以下是返回最接近值的查詢。在這裡,我們設定了一個使用者定義的變數,值為 6990。因此,現在我們需要獲取最接近 6990 的記錄 −

mysql> set @value=6990;
Query OK, 0 rows affected (0.00 sec)
mysql> select ProductAmount from DemoTable order by ABS(ProductAmount-@value) LIMIT 1;

這將生成以下輸出 −

+---------------+
| ProductAmount |
+---------------+
|          7000 |
+---------------+
1 row in set (0.00 sec)

更新於: 2019 年 10 月 4 日

148 次瀏覽

開啟你的 職業 生涯

完成課程,獲得認證

開始
廣告