2
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-01-28

以下のように、一つのカラムの中にカンマ区切りで複数の値が入っていて、例えば二つ目の値だけ取り出したいとき

+-------------+
| data        |
+-------------+
| aaa,bbb,ccc |
+-------------+



+--------+
| data_2 |
+--------+
| bbb    |
+--------+

こうする

SELECT
  SUBSTRING_INDEX(SUBSTRING_INDEX(data, ",", 2), ",", -1) AS data_2
FROM
  my_table_name;

ただし、↑の方法だと、区切り文字(カンマ)がないとそのまま値を返すので、バグの元になる

+-------------+
| data        |
+-------------+
| aaa,bbb,ccc |
| xxx         |
+-------------+



+--------+
| data_2 |
+--------+
| bbb    |
| xxx    |
+--------+

区切り文字がない場合はNULLを返すようにするには、こうする

SELECT
  IF(LOCATE(",", data) > 0,
    SUBSTRING_INDEX(SUBSTRING_INDEX(data, ",", 2), ",", -1),
    NULL
  ) AS data_2
FROM
  my_table_name;
+-------------+
| data        |
+-------------+
| aaa,bbb,ccc |
| xxx         |
+-------------+



+--------+
| data_2 |
+--------+
| bbb    |
| NULL   |
+--------+

区切り文字があったりなかったりする区切られた中の一つ目を抽出する場合はこんな感じ

SELECT
  IF(LOCATE(",", data) > 0,
    SUBSTRING_INDEX(SUBSTRING_INDEX(data, ",", 1), ",", -1),
    data
  ) AS data_1
FROM
  my_table_name;
+-------------+
| data        |
+-------------+
| aaa,bbb,ccc |
| xxx         |
+-------------+



+--------+
| data_1 |
+--------+
| aaa    |
| xxx    |
+--------+

かしこ。

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