[英]how to subtract value from 2 columns
使用PHP我想减去50列coins
如果它们的值> 50,如果不是,则从'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']."'");
“ coins”列中的值可能是100,而“ e-coins”列中的值可能是100
我想从“硬币”列中减去50,并保持电子硬币原样,但如果“硬币”列中的值小于50或没有任何值,那么从“电子硬币”列中减去怎么办?
假设您的colum coin数据类型是数字
$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 ....
可能是您的硬币和e-coins列不是数字,所以请尝试将其强制转换为整数
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'
似乎在直接更新的第二种情况下使用硬币会造成一些麻烦,所以我尝试使用带有sublery的内部联接来选择情况,并且这种方法可以正常工作
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`
您可以使用IF语句来实现此条件。 例如
UPDATE `users`
SET `coins` = IF(`coins` > 50, `coins` - 50, `coins`),
`e-coins` = IF(`coins` <= 50, `e-coins` - 50, `e-coins`)
WHERE id = <your id>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.