我在mysql中有很少的记录的表,所以我想将价格与price列进行比较。
这是我的桌子
id product price
1 p1 2000
2 p2 3000
3 p3 4000
4 p1 2500
如果我们想将'price'列与$ var ='1800'和product =“ p1”的值进行比较,则输出应该是第二高的记录,因为变量值小于price列的值
输出:
id product price
1 p1 2000
但是如果我们为价格列和product =“ p1”传递值$ var = 5000,则
输出应为:
id product price
4 p1 2500
答案 0 :(得分:0)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,product INT NOT NULL
,price INT NOT NULL
);
INSERT INTO my_table VALUES
(1,1,2000),
(2,2,3000),
(3,3,4000),
(4,1,2500);
mysql> SELECT *, ABS(price-1800) x FROM my_table WHERE product = 1 ORDER BY x LIMIT 1;
+----+---------+-------+-----+
| id | product | price | x |
+----+---------+-------+-----+
| 1 | 1 | 2000 | 200 |
+----+---------+-------+-----+
1 row in set (0.00 sec)
mysql> SELECT *, ABS(price-5000) x FROM my_table WHERE product = 1 ORDER BY x LIMIT 1;
+----+---------+-------+------+
| id | product | price | x |
+----+---------+-------+------+
| 4 | 1 | 2500 | 2500 |
+----+---------+-------+------+