0
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?

More than 1 year has passed since last update.

MySQLでテーブルデータの一部をSQLで移管する

Posted at

概要

特に外向けに難しいことを発信しようとしたわけでもなく、今後もたまに使いそうだと思った備忘、そのいくつか。

やりたいこと

table1 → table1_extendに一部データを移管(insert)したいが、わざわざスクリプトを組むのは面倒なので、SQL一発でやりたい。定期的な同期については今回は考えない(ホントはtriggerとかでやるんでしょうね。

対象テーブルの構造

table1
+--------------+-------------+
| Column       | Type        |
+--------------+-------------+
| table1_id    | INT         |
| table1column1| (data_type) |
| table1column2| (data_type) |
| table1column3| (data_type) |
+--------------+-------------+

table1_extend
+------------------+-------------+
| Column           | Type        |
+------------------+-------------+
| table1_id        | INT         |
| table_ext_column | VARCHAR(255)|
+------------------+-------------+

流したSQL

あくまで手法の紹介なので、果たして本当にこんなふうに移管をしたいシーンが有るかどうかはさておき、これでtable1 → table1_extendへのデータ登録ができます。

INSERT INTO table1_extended (table1_id, table_ext_column)
SELECT
  table1_id,
  CONCAT(
    COALESCE(table1column1, ''),
    COALESCE(table1column2, ''),
    COALESCE(table1column3, '')
  )
FROM
  table1;

おわり

雑にデータをガバッと入れたいときぐらいにしか使えませんが、プロトタイプつくったりとか、検証用に立てた環境を使いやすくしたいときとかには便利かもしれませんね。

0
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
0
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?