Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
24
Help us understand the problem. What is going on with this article?
@MasamotoMiyata

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

More than 5 years have passed since last update.

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キーワードも使えます。

24
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
24
Help us understand the problem. What is going on with this article?