Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql: How to convert positive value to negative while inserting

Tags:

sql

mysql

I have one table transaction with columns (id, amount) all positive integers and I have another table refund with same columns but here amount is expected to be negative. Now I want to use Insert into command to select from transaction and insert into refund. How can I make the amount negative while inserting. following is the query that I am trying.

INSERT INTO refund (id,amount) 
SELECT id, amount FROM `transaction`

Is there any way refund.amount always takes -ve values by default.

like image 843
Sunny Avatar asked Aug 12 '15 12:08

Sunny


3 Answers

INSERT INTO refund (id,amount) 
SELECT id, (0 - amount) as amount FROM `transaction`

as all data in transaction is positive.

INSERT INTO refund (id,amount) 
SELECT id, (-1 * amount) as amount FROM `transaction`
like image 158
Praveen Avatar answered Nov 11 '22 14:11

Praveen


If you, for some reason, are not guaranteed you get a positive amount every time you insert a new row, take the absolute value and multiply it by -1

INSERT INTO refund (id,amount) 
SELECT id, -1 * ABS(amount) FROM `transaction`

Otherwise, the ABS() part is not needed

INSERT INTO refund (id,amount) 
SELECT id, -1 * amount FROM `transaction`
like image 12
A Hocevar Avatar answered Nov 11 '22 12:11

A Hocevar


INSERT INTO refund (id,amount) 
SELECT id, (amount * -1) AS amount FROM `transaction`
like image 4
M0rtiis Avatar answered Nov 11 '22 14:11

M0rtiis