3
4

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 BYとORDER BYを同時に使うと動かない

Last updated at Posted at 2015-04-16
SELECT name FROM items GROUP BY name ORDER BY number;

これ、itemsテーブルからnumber順にユニークなnameを取ってきてくれるんだと思っていたのですが、飛んだ間違いでした。

どうもGROUP BYしてからORDER BYしているらしい・・・。
しかし、WHERE句に色々付け足してみたりするとまた順番が変わったりする。
調べてみてもどうにもならないっぽい

解決策1. サブクエリーを使う

SELECT DISTINCT name FROM (SELECT name FROM items ORDER BY number) AS sub

解決策2. サーバー側で頑張る

SELECT name FROM items ORDER BY number DESC;

ここまで取得して、返ってきたリストをサーバー側ユニークにする処理をする。

rubyだったら

sql = "SELECT name FROM items ORDER BY number DESC"
res = ActiveRecord::Base.connection.select(sql)
names = res.values
names.uniq
3
4
3

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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?