如何將正值轉換為負值,同時插入 MySQL?


我們首先建立一個表

mysql> create table recordsDemo
   -> (
   -> UserId int,
   -> Value int
   -> );
Query OK, 0 rows affected (0.52 sec)

現在使用插入命令在表中插入一些記錄。

查詢如下

mysql> insert into recordsDemo values(1,10);
Query OK, 1 row affected (0.17 sec)
mysql> insert into recordsDemo values(3,598);
Query OK, 1 row affected (0.18 sec)
mysql> insert into recordsDemo values(5,786);
Query OK, 1 row affected (0.25 sec)
mysql> insert into recordsDemo values(7,189);
Query OK, 1 row affected (0.16 sec)
mysql> insert into recordsDemo values(9,345);
Query OK, 1 row affected (0.14 sec)

使用選擇語句顯示錶中的所有記錄。

查詢如下

mysql> select *from recordsDemo;

以下是輸出

+--------+-------+
| UserId | Value |
+--------+-------+
| 1      | 10    |
| 3      | 598   |
| 5      | 786   |
| 7      | 189   |
| 9      | 345   |
+--------+-------+
5 rows in set (0.00 sec)

建立一個第二個表。建立第二個表的查詢如下

mysql> create table PositiveToNegativeValueDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Money int
   -> );
Query OK, 0 rows affected (0.83 sec)

以下是如何在插入時將正值轉換為負值

mysql> insert into PositiveToNegativeValueDemo(Id,Money)
   -> select UserId,(-1*Value) from recordsDemo;
Query OK, 5 rows affected (0.15 sec)
Records: 5 Duplicates: 0 Warnings: 0

現在使用選擇語句檢查表中的記錄。

查詢如下

mysql> select *from PositiveToNegativeValueDemo;

以下是輸出

+------+-------+
| Id   | Money |
+------+-------+
| 1    | -10   |
| 3    | -598  |
| 5    | -786  |
| 7    | -189  |
| 9    | -345  |
+------+-------+
5 rows in set (0.00 sec)

更新時間:30-Jul-2019

1K+ 瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告