LoginSignup
10
12

More than 5 years have passed since last update.

MySQL(MariaDB)で複数行が返ってきた結果を、1つのカラムに展開(縦を横に)

Posted at

概要

SQLで結果は縦だけど、横にまとめたい時があります。タグのデータとか。
具体的に、郵便番号のデータでやってみます(これは別に横に展開したいわけではないですが、、、)。
全国の郵便番号データを最速でMySQL(MariaDB)に入れてみる のデータです。

サンプルデータ

mysql
MariaDB [sampledb]> select id, zipcode, pref, city, street from zipcode where zipcode = '0288405';
+-------+---------+-----------+--------------------------+-----------+
| id    | zipcode | pref      | city                     | street    |
+-------+---------+-----------+--------------------------+-----------+
| 12700 | 0288405 | 岩手県    | 下閉伊郡田野畑村         | 大芦      |
| 12708 | 0288405 | 岩手県    | 下閉伊郡田野畑村         | 切牛      |
| 12726 | 0288405 | 岩手県    | 下閉伊郡田野畑村         | 浜岩泉    |
| 12729 | 0288405 | 岩手県    | 下閉伊郡田野畑村         | 真木沢    |
| 12732 | 0288405 | 岩手県    | 下閉伊郡田野畑村         | 南大芦    |
+-------+---------+-----------+--------------------------+-----------+
5 rows in set (0.00 sec)

同じ郵便番号で複数の地名が存在する↑のstreetのところですね。

SQL実行(group_concat)

MySQLの関数であるgroup_concatを使います。group_concatではDISTINCT、ORDER BY、SEPARATORが使えます。
group byにzipcodeを指定して、3つの郵便番号で検索してみます。

mysql
MariaDB [sampledb]> select zipcode, pref, city, group_concat(DISTINCT street ORDER BY id SEPARATOR '<>') from zipcode where zipcode in ('0288405', '0288406', '0288407') group by zipcode;
+---------+-----------+--------------------------+----------------------------------------------------------+
| zipcode | pref      | city                     | group_concat(DISTINCT street ORDER BY id SEPARATOR '<>') |
+---------+-----------+--------------------------+----------------------------------------------------------+
| 0288405 | 岩手県    | 下閉伊郡田野畑村         | 大芦<>切牛<>浜岩泉<>真木沢<>南大芦                       |
| 0288406 | 岩手県    | 下閉伊郡田野畑村         | 猿山<>年呂部<>七滝<>室場<>目名                           |
| 0288407 | 岩手県    | 下閉伊郡田野畑村         | 川平<>菅窪<>田野畑<>和野                                 |
+---------+-----------+--------------------------+----------------------------------------------------------+
3 rows in set (0.00 sec)

おお、なんて便利な。

10
12
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
10
12