1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MySQL 既存データを使ったデータでupdateを行う方法

Last updated at Posted at 2021-11-02

目的

  • 既存データに文字列を追加した値でupdateを行う方法をまとめる

何をしたいか

準備

  • 下記のSQLを実行してテーブルを作成し、update前の状態を作った。
    1. create database update_test;
    2. use update_test;
    3. create table update_tests (id int, url text);
    4. insert update_tests (id, url) values(1, '681ff186f4d6f9057135');
    5. insert update_tests (id, url) values(2, '545180847dcb9cb4ba8');
    6. 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 |
      +------+----------------------+
      

方法

  1. 下記SQLを実行して既存データを使ってupdateを実行する。

    update update_tests
    set url = concat('https://qiita.com/miriwo/items/', update_tests.url);
    
  2. 下記を実行して確認すると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 |
    +------+-----------------------------------------------------+
    

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?