38
28

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 5 years have passed since last update.

GROUP_CONCATでグルーピングした値をCONCAT

Last updated at Posted at 2015-05-01

GROUP_CONCATという便利な集約関数がMySQLにあって色々使えそうなので共有します。

例えばこんな感じテーブルshop_areaテーブルがあったとします。

shop_id area_id
1 21
1 3
2 14
2 15
3 33

で、これをshop_idでGROUP BYして下記のようなデータをSQL一発で取得可能です。

shop_id area_list
1 21/3
2 14/15
3 33

SQLはこんな感じ

SELECT shop_id, GROUP_CONCAT(area_id separator '/') as area_list 
  FROM shop_area 
  GROUP BY shop_id;

area_idが重複するような場合はGROUP_CONCAT(DISTINCT area_id separator '/')のように、DISTINCTキーワードも使えます。

38
28
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
38
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?