目的
- 既存データに文字列を追加した値でupdateを行う方法をまとめる
何をしたいか
-
下記のようにデータが格納されている
update_tests
テーブルがあったとする。id url 1 681ff186f4d6f9057135 2 545180847dcb9cb4ba8 3 eb09c065ee9bb7e8fe06 -
update文で下記の様にデータを修正したい。
id url 1 https://qiita.com/miriwo/items/681ff186f4d6f9057135 2 https://qiita.com/miriwo/items/545180847dcb9cb4ba8 3 https://qiita.com/miriwo/items/eb09c065ee9bb7e8fe06
準備
- 下記のSQLを実行してテーブルを作成し、update前の状態を作った。
create database update_test;
use update_test;
create table update_tests (id int, url text);
insert update_tests (id, url) values(1, '681ff186f4d6f9057135');
insert update_tests (id, url) values(2, '545180847dcb9cb4ba8');
insert update_tests (id, url) values(3, 'eb09c065ee9bb7e8fe06');
- 下記SQLを実行して下記と同じ表示が出力されることを確認する。
-
テーブル構造
mysql> show full columns from update_tests; +-------+------+--------------------+------+-----+---------+-------+---------------------------------+---------+ | Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment | +-------+------+--------------------+------+-----+---------+-------+---------------------------------+---------+ | id | int | NULL | YES | | NULL | | select,insert,update,references | | | url | text | utf8mb4_0900_ai_ci | YES | | NULL | | select,insert,update,references | | +-------+------+--------------------+------+-----+---------+-------+---------------------------------+---------+
-
格納されているデータ
mysql> select * from update_tests; +------+----------------------+ | id | url | +------+----------------------+ | 1 | 681ff186f4d6f9057135 | | 2 | 545180847dcb9cb4ba8 | | 3 | eb09c065ee9bb7e8fe06 | +------+----------------------+
-
方法
-
下記SQLを実行して既存データを使ってupdateを実行する。
update update_tests set url = concat('https://qiita.com/miriwo/items/', update_tests.url);
-
下記を実行して確認するとurlカラムの情報がupdateされたことがわかる。
mysql> select * from update_tests; +------+-----------------------------------------------------+ | id | url | +------+-----------------------------------------------------+ | 1 | https://qiita.com/miriwo/items/681ff186f4d6f9057135 | | 2 | https://qiita.com/miriwo/items/545180847dcb9cb4ba8 | | 3 | https://qiita.com/miriwo/items/eb09c065ee9bb7e8fe06 | +------+-----------------------------------------------------+