"How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL" Code Answer's

You're definitely familiar with the best coding language SQL that developers use to develop their projects and they get all their queries like "How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL" answered properly. Developers are finding an appropriate answer about How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL related to the SQL coding language. By visiting this online portal developers get answers concerning SQL codes question like How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL. Enter your desired code related query in the search bar and get every piece of information about SQL code related question on How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL. 

How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL

By Sore SkylarkSore Skylark on Jan 08, 2021
// These are the inputs you will be getting.
$pid = 321;
$qty = 7;

// Fetch all the relevent rows using the below query statement.
$select_sql = "select * from products_stock where pid = {$pid} and amount > 0";

// This will return the below array.
$data = [
    [
        'id' => 1,
        'zid' => 123,
        'pid' => 321,
        'amount' => 1,
    ],
    [
        'id' => 1,
        'zid' => 124,
        'pid' => 321,
        'amount' => 5,
    ],
    [
        'id' => 1,
        'zid' => 125,
        'pid' => 321,
        'amount' => 10,
    ],
];

$update_data = [];

// You can then loop through your rows to perform your logic
foreach  ($data as $row) {
    // Exit loop if qty is 0
    if ($qty == 0) {
        break;
    }

    $id = $row['id'];
    $amount = $row['amount'];

    // Subtract the required amount from qty.
    $qty -= $amount;
    $amount = 0;

    // If extra qty was consumed, add back to the amount.
    if ($qty < 0) {
        $amount =+ ($qty * -1);
        $qty = 0;
    }

    // Update you data here or the best practice would be to avoid sql in a loop and do a bulk update.
    // You can do this based on your requirement.
    // $update_sql = "update products_stock set amount = {$amount} where id = {$id}";

    // Prepare date for bulk update
    $update_data []= [
        'id' => $id,
        'amount' => $amount,
    ];

    echo "Qty {$qty} | Amt {$amount} \n";
    echo "--------\n";
}

// Bulk update all your rows
if (count($update_data) > 0) {
    $this->db->update_batch('products_stock', $update_data, 'id'); 
}

echo "\n";
echo "Balance Qty ". $qty . "\n";

Source: stackoverflow.com

Add Comment

0

All those coders who are working on the SQL based application and are stuck on How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL can get a collection of related answers to their query. Programmers need to enter their query on How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL related to SQL code and they'll get their ambiguities clear immediately. On our webpage, there are tutorials about How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL for the programmers working on SQL code while coding their module. Coders are also allowed to rectify already present answers of How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL while working on the SQL language code. Developers can add up suggestions if they deem fit any other answer relating to "How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL". Visit this developer's friendly online web community, CodeProZone, and get your queries like How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL resolved professionally and stay updated to the latest SQL updates. 

SQL answers related to "How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL"

View All SQL queries

SQL queries related to "How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL"

How to update field to subtract value to existing value if that value is lesser than the existing value balance value should be subtract from the next coloumn in MySQL postgresql update sequence next value com.mysql.cj.exceptions.InvalidConnectionAttributeException more than one time zone. You must configure either the server or JD value if you want to utilize time zone support. mysql last day of next month how to populate a table in MySQL from and existing csv file sql update with field from another table can't connect to local mysql server through socket '/var/lib/mysql/mysql.sock' sql subtract C# mysql update statement set value to null mysql update value You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column. update left join mysql update part of a string in mysql how to update an attribute in MySQL update substring in mysql update mysql mysql update query mysql select update same table update using case in mysql grant update privilege command in mysql mysql update sequence with order by update query with between in mysql update multiple columns in mysql order by with more than one column ERROR: column "id" specified more than once wordpress delete post revisions older than date "sql" less than date query sqlachemy date less than in sql display the employees whose salary is less than average salary sql where date greater than sqlalchemy existing db file get the mysql table columns data type mysql ModuleNotFoundError: No module named 'mysql.connector'; 'mysql' is not a package add multiple field in table sql drop a field in psql django Fatal error: Uncaught PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'autos_id' in 'field list' in update and keep original value sql Check if value exisits update or insert sQL mysql default value replace null value within column mysql conpare to null value in mysql stack overflow provide hardcoded value in the mysql query mysql add to value concat column value of same user in mysql mysql group rows with same value multi value column mysql mysql find the row ites of the hoghest value at on column mysql check if value exists update with inner join sql update query sql server update c# example code pl sql trigger determine if insert or update or delete sql oracle update multiple rows update column data type postgres update with inner join postgres sql update from select update a row in sql t-sql update from select update from select join how to update data in sql UPDATE command in SQL update from select oracle automatically update database last seen datetime in sql update sql sintassi deny select insert update delete sql update database collation in postgresql update all linkedserver tables with openquery on db Update All tables COLLATE DATABASE_DEFAULT postegresql update to null sql server update column based on another table how to update sql server version update/delet in mssql oracle c# multiple update sql update sqlaclehmy sqlalchemy.orm.evaluator.UnevaluatableError: Cannot evaluate BinaryExpression with operator update from select update a table with values from another table update query for multiple columns update from select postgresql install mysql from ubuntu cast string to datetime mysql mysql CURRENT_TIMESTAMP() mysql date format unix timestamp create table mysql how ot change name of column mysql bulk kill mysql processlist how to check username in mysql command line how to get current mysql version how to create a variable in mysql set utf8mb4 mysql tables mysql see users and passwords mysql show variables mysql delete row django mysql settings mysql import gz mysql version check cmd mysql date between two dates group by mysql and concatenate string how to show all users in mysql how to alter table column name in mysql mysql url mysql remote connection command line mysql install windows 10 mysql timestamp to date mysql get last day of month change mysql password from command line mysql check date range login mysql show all users in mysql drop table in mysql mysql number format mysql insert on dupèlicate mysql string length mysql format date mysql to date create user mysql debian 10 mysql select else if grant revoke privileges to mysql username how to run mysql in git bash ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client vs code SELECT User,Host FROM mysql.user; mysql' is not recognized as an internal or external command, set database timezone mysql input in mysql mysql debezium select tables with name like mysql set id count mysql mySql insert row create temporary table in mysql ubuntu stop mysql from starting on boot mysql get longest string in column mysql run sql file mysql count vs sum host 127.0 0.1 is not allowed to connect to this mysql server mysql backup database how to run mysql on terminal mac create a table with an id in mysql mysql load csv into table mysql create stored procedure ubuntu reset mysql root password alter table add column and foreign key mysql mysql dump specific tables select case mysql mysql pivot how to change mysql root password in windows 10 date conversion in mysql column mysql select and count left join limit offset order by mysql mysql workbench tutorial add column mysql with foreign key mysql if else mysql connector/python query example mysql version group_concat mysql mysql #1093 - You can't specify target table error mysql limit mysql show current connections mysql generate uuid ubuntu install mysql 8.0 mysql backup database command line insert mysql how to connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) mysql check table exists alter table mysql select where mysql installing mysql on ubuntu mysql dump with table query second height salary mysql alphabetical order mysql docker conectar a mysql de otro contenedor mysql last friday of current month how to create a table based on another table in mysql mysql multiple order by extract month from date in mysql mysql vs postgresql how to import mysql database command line mysql 8 geo to json list mysql tables and views mysql multiple primary keys mysql backup sh script and remove old import sql file mysql commadn line how to export table data from mysql table in sql format mysql regex exact match how to connect mysql local server mysql workbench download query in mysql enable full text search mysql mysql order by desc null last C# mysql data reader from two tables MySQL WHERE mysql error 1251 how to use mysql shell in windows how to delete table in mysql generate random & unique mysql string how to open mysql in docker mysql trigger to delete old data connexion mysql mysql changer nom table reading mysql data in python

Browse Other Code Languages

CodeProZone