如何编写Mysql查询以将变量值与列值进行比较并获得最高的记录或第二高的记录

时间:2018-11-25 11:53:10

标签: mysql

我在mysql中有很少的记录的表,所以我想将价格与price列进行比较。

  1. 如果变量的传递值小于价格列的值,则获得产品ID =“ p1”的第二高记录
  2. 如果变量的传递值大于价格列值,则获得产品ID =“ p1”的最高记录

这是我的桌子

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

1 个答案:

答案 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 |
+----+---------+-------+------+