Select 来自 SQL table 的最大值应用于另一个 table
Select MAX value from SQL table to apply in another table
我的站点是 Prestashop (1.5.6.2)。
我的一些产品可以根据订购的产品数量有较低的价格。我想在某处提及产品的最低价格(因此我需要最大降价才能实现这一目标)。
Table1个(我的价格在这个table)
+------------+-------+
| id.product | price |
+------------+-------+
| 1 | 1000 |
+------------+-------+
Table2(我的减法是在这个table)
+------------+--------+-----------+
| 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)
有什么想法吗?
试试这个:
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
如果您只想显示修改后的价格,请使用:
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;
我的站点是 Prestashop (1.5.6.2)。
我的一些产品可以根据订购的产品数量有较低的价格。我想在某处提及产品的最低价格(因此我需要最大降价才能实现这一目标)。
Table1个(我的价格在这个table)
+------------+-------+
| id.product | price |
+------------+-------+
| 1 | 1000 |
+------------+-------+
Table2(我的减法是在这个table)
+------------+--------+-----------+
| 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)
有什么想法吗?
试试这个:
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
如果您只想显示修改后的价格,请使用:
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;