简体   繁体   中英

update record by adding a value to existing value sql

I am using REPLACE statement to insert/update records in a table with composite primary key. How can I add a new value to existing value and update the record using REPLACE statement? Here's my sql:

function leaveBalanceRecord($f3)
{
    $userID = $this->f3->get('userID');
    $leaveType = $this->f3->get('leaveType');
    $leaveBalance = $this->f3->get('leaveBalance');
    $sql = "REPLACE INTO users_leave_balance 
    (user_id, period, leave_type, leave_balance, rollable_till_date)
    VALUES ($userID, '2017-01-03', $leaveType, $leaveBalance, 3.05)";
    $results = $this->db->exec($sql);
    return $results;
}

Eg. I have a following record:

user_id  |  period  |  leave_type  |  leave_balance
134      |  2017-01 |  1           |  10.0

Now if user tries to insert another record with user_id - 134, period - 2017-01, leave_type - 1, and leave_balance - 3, I need to add the current balance 3 to existing balance 10.0 and update 13.0

user_id, period, and leave_type columns constitute a Composite key

This won't work with REPLACE INTO , but you can use a combination of INSERT INTO , ON DUPLICATE KEY and UPDATE while UPDATE will provide a way to concat new with existing data.

Example:

INSERT INTO users SET userid = 8, username = "Foobar"
ON DUPLICATE KEY
UPDATE username = CONCAT(username, "123")

This will basically try to insert a new user with the userid "8" and the username "Foobar". The userid is my primary key. If it exists, it will instead update the existing user and append "123" to its username.

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