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 カラムのデータを入れ替える

Last updated at Posted at 2022-07-24

やりたいこと

MySQLを使ってテーブルのカラムのデータを入れ替えたい。
下記のarticleテーブルで、titleとcontentのカラムの中身を入れ替えてみる。
スクリーンショット 2022-07-24 15.24.37.png

実行するSQL

.sql
UPDATE article SET title=CONCAT(title, ':', content),
content=SUBSTRING_INDEX(title, ':', 1),
title=SUBSTRING_INDEX(title, ':',  -1);

*contentに:が使われていないことを前提とする。

id=1で動きの説明をする。

title=CONCAT(title, ':', content),
titleとcontentの間に':'の文字を挟んで結合。
->titleカラムはタイトル1:コンテンツ1のようになる。

content=SUBSTRING_INDEX(title, ':', 1),
contentカラムに①で連結した文字列の:より前の文字列を取得させる。
->タイトル1となる。

title=SUBSTRING_INDEX(title, ':', -1);
titleカラムに①で連結した文字列の:より後の文字列を取得させる。
->コンテンツ1となる。

↓上記を実行するとtitleとcontentの中身が入れ替わった。
スクリーンショット 2022-07-24 18.37.13.png

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?