I want update price in table A using if statement, I have tried it but it can't be that I can only do calculations by calling id one by one, how to calculate the price directly? this is the table:
TABLE A
-------------------------
id | type | total | price
-------------------------
1 | a1 | 80 | [ ]
2 | a2 | 50 | [ ]
3 | a2 | 15 | [ ]
this is the if statement
if($type=='a1')
{
$price1=1050;
$price2=1500;
$price3=2000;
if($total <= 10)
{
$price = $total*$price1;
}
elseif($total <= 20)
{
$a = 10;
$remtotal = $total-$a;
$price = ($a*$price1)+($remtotal*$price2);
}
elseif($total > 20)
{
$a = 10;
$b = 10;
$remtotal = ($total-$a)-$b;
$price = ($a*$price1)+($b*$price2)+($remtotal*$price3);
}
}
elseif($type=='a2')
{
$price1=2100;
$price2=3000;
$price3=4000;
if($total <= 10)
{
$price = $total*$price1;
}
elseif($total <= 20)
{
$a = 10;
$remtotal = $total-$a;
$price = ($a*$price1)+($remtotal*$price2);
}
elseif($total > 20)
{
$a = 10;
$b = 10;
$remtotal = ($total-$a)-$b;
$price = ($a*$price1)+($b*$price2)+($remtotal*$price3);
}
}
SELECT id,type,total,price FROM TABLE A WHERE id='id'
UPDATE TABLE A SET price='$price' WHERE id=id"
I can count one by one by calling id but which I hope can immediately count all at once
expected result
-------------------------
id | type | total | price
-------------------------
1 | a1 | 80 | [145500]
2 | a2 | 50 | [171000]
3 | a2 | 15 | [28500]
How to do it?
Solved
I create 2 table
TABLE A
-------------------------
id | type | total | price
-------------------------
1 | a1 | 80 | [ ? ]
2 | a2 | 50 | [ ? ]
3 | a2 | 15 | [ ? ]
TABLE B
| type | price1 | price2 | price3 |
| ---- | ------ | ------ | ------ |
| a1 | 1050 | 1500 | 2000 |
| a2 | 2100 | 3000 | 4000 |
| a2 | 2100 | 3000 | 4000 |
this is the code
UPDATE tabelA ta, tabelB tb
SET ta.price = ( CASE
WHEN ta.type = 'a1' AND ta.total <= 10
THEN ta.total * tb.price1
WHEN ta.type = 'a1' AND ta.total <= 20
THEN (10 * tb.price1) + ((ta.total - 10) * tb.price2)
WHEN ta.type = 'a1' AND ta.total > 20
THEN (10 * tb.price1) + (10 * tb.price2) + (((ta.total - 10) - 10) * tb.price3)
WHEN ta.type = 'a2' AND ta.total <= 10
THEN ta.total * tb.price1
WHEN ta.type = 'a2' AND ta.total <= 20
THEN (10 * tb.price1) + ((ta.total - 10) * tb.price2)
WHEN ta.type = 'a2' AND ta.total > 20
THEN (10 * tb.price1) + (10 * tb.price2) + (((ta.total - 10) - 10) * tb.price3)
END )
WHERE ta.type = tb.type
TABLE A
-------------------------
id | type | total | price
-------------------------
1 | a1 | 80 | [145500]
2 | a2 | 50 | [171000]
3 | a2 | 15 | [28500]
SUMquery?