简体   繁体   English

PHP MySQL Update减去没有单独SELECT查询的变量

[英]PHP MySQL Update minus variable without separate SELECT Query

I know there is a way to do this. 我知道有办法做到这一点。 Basically I have the variable $amount and want to take that away from the column amount in the table stock. 基本上我有变量$amount并希望从表库存中的列数量中取出它。

The problem is I normally run a select query find out the value then deduct the variable and run another update query. 问题是我通常运行一个select查询找出值然后扣除变量并运行另一个更新查询。

What is the syntax to run a single update that will just minus the value. 运行单个更新的语法是什么,只会减去该值。

All help appreciated. 所有帮助赞赏。

It's as simple as it seems. 这看起来很简单。 Parentheses are optional in this example. 在此示例中,括号是可选的。 Be sure to use the appropriate condition in your WHERE clause! 务必在WHERE子句中使用适当的条件!

$qry = "UPDATE table SET column = (column - $amount) WHERE somecondition;";

The variable $amount is assumed to be properly escaped already, according to the MySQL API you are using, or better yet, a parameter to a prepared example, as in PDO: 根据您正在使用的MySQL API,假设变量$amount已经正确转义,或者更好的是,作为准备示例的参数,如在PDO中:

$qry = "UPDATE table SET column = (column - :amount) WHERE somecondition;";
$stmt = $db->prepare($qry);
$stmt->execute(array(':amount' => $amount));

Try something like this: 尝试这样的事情:

UPDATE table_name SET amount = amount - $amount WHERE primary_key = value LIMIT 1

If you want to make sure amount doesn't go below zero: 如果你想确保amount不低于零:

UPDATE table_name SET amount = amount - $amount WHERE primary_key = value AND amount >= $amount LIMIT 1

do you want below? 你想要下面吗?

UPDATE table_name
SET amount = amount -$amount
WHERE primary = id

Out of curiosity are you getting $variable from some other sql select? 出于好奇,你从其他一些sql select获得$ variable? Like perhaps a parts list or something? 或许像零件清单或其他什么? It could potentially be much faster to run the entire thing inside a stored procedure or compound select. 在存储过程或复合选择中运行整个事物可能会快得多。

If that $variable is static or locally generated disregard. 如果$ variable是静态的或本地生成的无视。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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