[英]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.