简体   繁体   中英

Select MAX value from SQL table to apply in another table

My site is a Prestashop (1.5.6.2).

Some of my product can have a lower price according to the number of product ordered. And I'd like to mention somewhere the minimum price of the product (so I need the maximum amount of reduction to make this happen).

Table 1 (my price is in this table)

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

Table 2 (my reduction is in this table)

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

According to this is example, I would like to display:

Product 1 from 700 euros

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

(I'd like to UPDATE the existing price because this is a second field which I create actually called price_from but i didn't want to make the example too complicate)

This is my code so far:

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)

Any ideas?

If you only want to display the modified price use this:

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

If you want to modify the price try this:

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; 

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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