MySQLで、日付の一部を抽出して、月日だけを見てソートしたい。

what

MySQLで、日付の一部を抽出して月日だけを見てソートしたい。

以下のデータは、hogeテーブルのbirthdayカラムに保存されている。

hogeテーブル

id birthday
1 1985-05-02
2 1980-05-03
3 1979-05-01
4 1981-03-15

上記を

hogeテーブル

id birthday
3 1979-05-01
1 1985-05-02
2 1980-05-03

このように、5月の中で新しい順にソートして、出力したい。

結論

SELECT *,MONTH(birthday)+DAY(birthday) FROM hoge where MONTH(birthday) = 5 order by MONTH(birthday)+DAY(birthday);
  • 出力結果
id birthday
3 1979-05-01
1 1985-05-02
2 1980-05-03

今回学んだこと

MONTH(カラム名)、DAY(カラム名)で月と日が取得できる><

初めて知りました・・・。

MySQL :: MySQL 5.6 リファレンスマニュアル :: 3.3.4.5 日付の計算

SELECT * FROM hoge where MONTH(birthday) = 5;

これで5月の人が取れる。

  • 出力結果
id birthday
1 1985-05-02
2 1980-05-03
3 1979-05-01
一時的に計算結果を新しいカラムで持つ
SELECT *,MONTH(birthday)+DAY(birthday) FROM hoge;
  • 出力結果
id birthday MONTH(birthday)+DAY(birthday)
1 1985-05-02 7
2 1980-05-03 8
3 1979-05-01 6
4 1981-03-15 18


今回のクエリの時だけ生成されますので、テーブルが壊れたりしません。

一時的に計算結果を出力したカラムでorder byする
SELECT *,MONTH(birthday)+DAY(birthday) FROM hoge order by MONTH(birthday)+DAY(birthday);
  • 出力結果
id birthday MONTH(birthday)+DAY(birthday)
3 1979-05-01 6
1 1985-05-02 7
2 1980-05-03 8
4 1981-03-15 18
もちろんwhere句も加えることができる。これが結論。
SELECT *,MONTH(birthday)+DAY(birthday) FROM hoge where MONTH(birthday) = 5 order by MONTH(birthday)+DAY(birthday);
  • 出力結果
id birthday MONTH(birthday)+DAY(birthday)
3 1979-05-01 6
1 1985-05-02 7
2 1980-05-03 8

Rails(1.2.3)のコードに置き換えてみる

find(:all, :select=>"*,MONTH(birthday)+DAY(birthday)",:conditions=>["MONTH(birthday) = ?", 5], :order => MONTH(birthday)+DAY(birthday))

環境