こんな便利な機能があるのを知らなかったなんて情弱でした。
記事とカテゴリーをマッピングしたテーブルとして以下のようなものがあるとします。よくある多対多のテーブルです。
posts_categoriesテーブル
post_id | category_id |
---|---|
1 | 1 |
1 | 3 |
1 | 5 |
2 | 2 |
2 | 3 |
2 | 4 |
2 | 5 |
3 | 2 |
これに以下のSQLを実行すると
select post_id, group_concat(distinct category_id separator \',\') as result from posts_categories group by post_id;
このような結果が得られます。
post_id | result |
---|---|
1 | 1,3,5 |
2 | 2,3,4,5 |
3 | 2 |
PHP等の言語からMySQLを呼び出す場合など、これでデータを取得してexplode(',', $result);
とするだけで、category_idの配列を取得することが出来て便利です。