繁体   English   中英

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

[英]Select MAX value from SQL table to apply in another table

我的网站是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)

有任何想法吗?

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

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; 

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM