具有相同id的列上的UPDATE表值(SET min值)

时间:2018-02-06 14:08:25

标签: mysql

id  |  price
100 |  12.5
101 |  15.8
100 |  20.8
99  |  45.2
101 |  11.7
79  |  10.4
100 |  14.7
101 |  18.8

我正在寻找解决此问题的方法。

我想使用MySQL UPDATE命令...

这样的结果
id  |  price
100 |  12.5
101 |  11.7
100 |  12.5
99  |  45.2
101 |  11.7
79  |  10.4
100 |  12.5
101 |  11.7

有任何解决方案吗?

3 个答案:

答案 0 :(得分:-1)

尝试更新加入子查询,查找每个id组的最低价格:

UPDATE yourTable t1
INNER JOIN
(
    SELECT id, MIN(price) AS min_price
    FROM yourTable
    GROUP BY id
) t2
    ON t1.id = t2.id
SET t1.price = t2.min_price;

答案 1 :(得分:-1)

UPDATE t

 SET    t.Price= o.MinPrice

FROM   yourTable t

INNER JOIN (select id , min(price) MinPrice from yourTable group by id ) o ON o.id= t.id

答案 2 :(得分:-1)

尝试使用Simple子查询来更新表的值

update myTable t1, 
(select * from (select * from myTable order by price) x group by id) t2 
set t1.price = t2.price where t1.id = t2.id;

在执行查询之前,数据如下:

+------+-------+
| id   | price |
+------+-------+
|  100 |  12.5 |
|  101 |  15.8 |
|  100 |  20.8 |
|   90 |  45.2 |  
|  101 |  11.7 |
|   79 |  10.4 |
|  100 |  14.7 |
|  101 |  18.8 |
+------+-------+

执行后:

+------+-------+
| id   | price |
+------+-------+
|  100 |  12.5 |
|  101 |  11.7 |
|  100 |  12.5 |
|   90 |  45.2 |
|  101 |  11.7 |
|   79 |  10.4 |
|  100 |  12.5 |
|  101 |  11.7 |
+------+-------+