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

【MySQL】GROUP BY句の書き方

0
Posted at

どんなミスをした?

前提

SQL徹底指南書に書いてあるSQLを実行していた。
クエリを見て書くのではなく、やりたいことだけを見て自力で書くことができるかを試していた。
(※本題に入る手前の部分ではあったが...)

実際のミス

ミスがあるコード

SELECT std_id, club_id
FROM StudentClub
GROUP BY std_id;

何がダメ?

std_idおよびclub_idには重複しているレコードがある。
その状態でstd_idはまとめているのに、club_idはまとめられていないので、どのレコードを出力すればいいのかわからない。
よってエラーが発生した。

どのように書けばいいのか?

SELECT std_id, MAX(club_id)
FROM `StudentClub`
GROUP BY std_id;

これなら同じstd_idが複数のclub_idを持っていても、一意に定めることができる。
(※MAXでなくても集約関数であればなんでもいいか?)

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