LoginSignup
1
0

More than 5 years have passed since last update.

Mariadb で ユーザー定義変数を使って値をコピー

Posted at

SQL でユーザー定義変数を使って値をコピーします。

スタート時点のテーブルの状況

> select * from cities;
+-------+--------+------------+------------+
| id    | name   | population | date_mod   |
+-------+--------+------------+------------+
| t3321 | 岡山   |     529176 | 2003-09-20 |
| t3322 | 倉敷   |     791835 | 2003-02-15 |
| t3323 | 津山   |     163754 | 2003-08-18 |
| t3324 | 玉野   |     369172 | 2003-01-09 |
| t3325 | 笠岡   |     237451 | 2003-03-04 |
| t3326 | 井原   |     518397 | 2003-05-21 |
| t3327 | 総社   |     248156 | 2003-07-23 |
| t3328 | 高梁   |     478294 | 2003-10-26 |
| t3329 | 新見   |     863751 | 2003-12-15 |
+-------+--------+------------+------------+

id が t3328 の population を t3329 の population にコピーします。

1) @vx に値を代入します。

> select population into @vx from cities where id = 't3328';
Query OK, 1 row affected (0.000 sec)

2) @vx の値を使って更新します。

> update cities set population=@vx where id='t3329';
Query OK, 1 row affected (0.068 sec)
Rows matched: 1  Changed: 1  Warnings: 0

3) 結果を確認

> select * from cities;
+-------+--------+------------+------------+
| id    | name   | population | date_mod   |
+-------+--------+------------+------------+
| t3321 | 岡山   |     529176 | 2003-09-20 |
| t3322 | 倉敷   |     791835 | 2003-02-15 |
| t3323 | 津山   |     163754 | 2003-08-18 |
| t3324 | 玉野   |     369172 | 2003-01-09 |
| t3325 | 笠岡   |     237451 | 2003-03-04 |
| t3326 | 井原   |     518397 | 2003-05-21 |
| t3327 | 総社   |     248156 | 2003-07-23 |
| t3328 | 高梁   |     478294 | 2003-10-26 |
| t3329 | 新見   |     478294 | 2003-12-15 |
+-------+--------+------------+------------+

4) @vx の値の表示

> select @vx;
+--------+
| @vx    |
+--------+
| 478294 |
+--------+
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0