从SQL表中选择MAX值以应用于另一个表

时间:2015-03-04 10:43:06

标签: php mysql max

我的网站是Prestashop(1.5.6.2)。

根据订购的产品数量,我的部分产品价格较低。我想在某处提到产品的最低价格(所以我需要最大限度的减少才能实现这一点)。

表1(我的价格在此表中)

+------------+-------+
| id.product | price |
+------------+-------+
|          1 |  1000 |
+------------+-------+

表2(我的减少在此表中)

+------------+--------+-----------+
| id.product | amount | reduction |
+------------+--------+-----------+
|          1 |      2 |       100 |
|          1 |      3 |       200 |
|          1 |      4 |       300 |
+------------+--------+-----------+

根据这个例子,我想显示:

产品1起700欧元

1000 - 300 (which is the maximum reduction on product.id 1) = 700

(我想更新现有价格,因为这是我创建的第二个字段,实际上称为price_from,但我不想让这个例子太复杂了)

到目前为止,这是我的代码:

UPDATE table1 
INNER JOIN table2 ON (table1.id_product = table2.id_product )
SET table1.price = table1.price - (SELECT MAX(table2.reduction) FROM table2 GROUP BY id_product)

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

如果您只想显示修改后的价格,请使用:

select t1.id_product, (price - max_reduction) as new_price 
from table1 t1 inner join (
    select id_product, max(reduction) max_reduction FROM table2
    GROUP BY id_product
) t2 on t1.id_product = t2.id_product

如果您想修改价格,请尝试:

update table1 t1, (
    select id_product, MAX(t2.reduction) as max_reduction 
    FROM table2 t2
    GROUP BY id_product) t2
SET t1.price = t1.price - t2.max_reduction
WHERE t1.id_product = t2.id_product; 

答案 1 :(得分:0)

试试这个:

update table1 
inner join (SELECT max(`reduction`) as maxprice, id FROM table2 group by id ) t
on
table1.id = t.id
SET
table1.price = table1.price - t.maxprice