MySQL DB更新2值:1增加& 1减少

时间:2013-11-08 23:15:56

标签: php mysql

我的数据库中有一个名为member的数据库,其中包含字段'personID &余额。

如果用户1的余额为20.00,并希望向用户2发送10.00,那么减少用户1余额和更新用户2余额的最佳方法是什么?

任何帮助/建议都会很棒!

提前致谢

更新

CODE:

 $accountfrom=$_POST[accountfrom];
 $accountto=$_POST[accountto];
 $amount=$_POST[amount]; 
$con = mysql_connect("localhost","cl49-XXX","XXX");
if (!$con) 
  {
   die('Could not connect: ' . mysql_error());
   }

mysql_select_db("cl49-XXX", $con)or die( "Unable to select database");


$result = mysql_query("UPDATE member
SET balance = IF(personID = $acountfrom, balance-$amount, balance+$amount)
WHERE personID IN ($accountfrom, $accountto)")
 or die(mysql_error());

结果:

  

'您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   'balance-100.00,balance + 100.00)附近的人员ID IN(84587745,   98554130)'第2行'

1 个答案:

答案 0 :(得分:3)

UPDATE member
SET balance = IF(personID = 1, balance-10, balance+10)
WHERE personID IN (1, 2)

限制转移到发件人的余额:

UPDATE member m1
CROSS JOIN (SELECT LEAST(10, balance) transfer
      FROM member
      WHERE personID = 1) m2
SET m1.balance = IF(personID = 1, balance - transfer, balance + transfer)
WHERE personID in (1, 2)