2
0

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.

MySQLのgroup_concatを使えば複数レコードの値を一気に取得できる

Last updated at Posted at 2020-03-30

こんな便利な機能があるのを知らなかったなんて情弱でした。

記事とカテゴリーをマッピングしたテーブルとして以下のようなものがあるとします。よくある多対多のテーブルです。

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の配列を取得することが出来て便利です。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?