简体   繁体   中英

how to subtract value from 2 columns

Using PHP I want to subtract 50 of column coins if have value > 50 , if not then subtract from 'e-coins' .

Users Table:

this is the sample 
id |user |coins |e-coins| 
1 |axxx |100 |100 | 
2 |bxxx |100 |0 | 
3 |cxxx |0 |100 |
and this is the result i want
1 |axxx |50 |100 | 
2 |bxxx |50 |0 | 
3 |cxxx |0 |50 |

PHP:

    $db->Query("UPDATE `users` SET `coins`=`coins`-'50' WHERE `id`='".$sit['user']."'");

value in column 'coins' could be 100 and i column 'e-coins' could be 100

I want to subtract from column 'coins' 50 and leave e-coins as it is , but in case column 'coins' have less than 50 or not have any value so subtract from column 'e-coins' How can i do this ?

Assuming your colum coins data type is numeric

$db->Query("
    UPDATE `users` 
    SET `coins`= case when `coins` > 50 then  coins - 50  else coins end,
        `e-coins` = case when `coins` <= 50 then `e-coins` - 50  else `e-coins` end 

where  .... 

could be you coins and e-coins column are not numeric so try cast as integer

  UPDATE users 
  SET coins= case when (CAST(coins) AS INT coins)  > 50 then coins - 50 else coins end,
   `e-coins` = case when(CAST(coins) AS INT coins)  <= 50 then `e-coins` - 50 else `e-coins` end 
   WHERE id= 'id' 

seems that the use of coin in second case in direct update create some trouble so i have tried using a inner join with sublery for select the case and this houd work correctly

update users 
inner join (
 select  id, 
       case
        when  coins > 50 
          then coins - 50
          else coins
    end coins ,
    case
        when coins <= 50
        then `e-coins` - 50
        else `e-coins`
     end `e-coins` 
from users  ) t  ON t.id = users.id  
     and users.id = your_id_value 
set users.coins = t.coins,
    users.`e-coins` = t.`e-coins` 

You can use IF statement to implement this condition. For example

UPDATE `users` 
SET `coins` = IF(`coins` > 50, `coins` - 50, `coins`), 
    `e-coins` = IF(`coins` <= 50, `e-coins` - 50, `e-coins`) 
WHERE id = <your id>

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