LoginSignup
8
12

More than 5 years have passed since last update.

MYSQLの関数 GROUP_CONCAT

Posted at

 1対多テーブルの処理周りでのムチャぶりに対応してくれる、GROUP_CONCAT関数です。

GROUP_CONCAT(
    [DISTINCT] expr [,expr ...]
    [ORDER BY {unsigned_integer | col_name | expr}
    [ASC|DESC] [,col_name ...]]
    [SEPARATOR str_val])

要は使い方としてはこんなかんじで。

SELECT 
    users.*,
    GROUP_CONCAT(
        DISTINCT users.id
        ORDER BY users.id DESC SEPARATOR ','
    ) as user_list
    FROM users
    GROUP BY users.area;

コレでuser_list列にエリア毎のユーザIDの一覧が,区切りで入ってくる。

セパレータはSEPARATORで指定して、デフォルトは,
INT列とかを結合して,スクリプト側でSEPARATORによる分割、とかしたら楽に処理できる、はず。

後々分割すること考えたら文字列とかの結合には不向きな気がする。

ORDER BY側のデフォルトはASC。特に指定しなくてもOK

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