1

I have a table

 accountdetails

with fields

customerid,balance,account id

Now Im trying to update this through my node app where when I transfer amount, in one record the value should be debited and in another it should be credited

var data = {customerid,transferamount,accountid};


 con.query('update accountdetails set balance = balance-? WHERE customerid = ? ,
 [data.transferamount,data.customerid]')

con.query('update  accountdetails set balance = balance+? WHERE accountid = ?,
[data.transferamount,data.accountid]')

So currently I have two commands to do this how can we limit this to one command since both are basically updating single table.

Any idea

user7350714
  • 365
  • 1
  • 6
  • 20

4 Answers4

0

Agree with @kawadhiya21, maybe better don't do it... you have to benchmark both cases to figure out performance, but in general, it is possible:

sql = 'update accountdetails';
sql += 'set balance = if(customerid = ?, balance - ?, if(accountid = ?, balance + ?, balance) ) ';
sql += 'where customerid = ? or accountid = ?';
con.query(sql, [
    data.customerid,
    data.transferamount,
    data.accountid,
    data.transferamount,
    data.customerid,
    data.accountid
]);
cn007b
  • 16,596
  • 7
  • 59
  • 74
0

Good day,

Yes these two commands must remain to update your data, since you have different conditions on your commands.

Your first command condition is WHERE customerid, while the other command condition is WHERE accountid, so it is not possible to combine these into one single command.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
0

One of the best practices is utilising mysql's Triggers. These are programmable database objects that do the job. What you basically describe is an AFTER UPDATE trigger. For Example:


CREATE TRIGGER doTheJob AFTER UPDATE ON accountdetails
FOR EACH ROW

BEGIN
UPDATE accountdetails
SET balance = +? WHERE accountid = ?

  END;
  DELIMITER ;

More info specifically on AFTER UPDATE triggers here More info on triggers here

0

Another way is to use stored procedures to accomplish this: https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-stored-procedures.html

With a stored procedure you can add 3 parameters (customerid, transferamount, accountid) and hide all the internal details of the SQL calls (for instance the solution from Vladimir Kovpak)

Erik Oppedijk
  • 3,496
  • 4
  • 31
  • 42