Skip to content

Instantly share code, notes, and snippets.

@kazuho
Last active December 24, 2015 11:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazuho/6791809 to your computer and use it in GitHub Desktop.
Save kazuho/6791809 to your computer and use it in GitHub Desktop.
mysql-ranking-engineの使い方
-- テーブルを作る
CREATE TABLE t (
  user_id int unsigned not null,
  score int not null,
  ranking int unsigned,                -- rankingというカラムがエンジンによって自動更新される
  primary key (user_id),
  key ranking (score)                -- ランキング用のindex                  
) engine=ranking;

-- テーブルに書く
REPLACE INTO t (user_id,score) VALUES (123,300);  -- rankingカラムはnullしか書き込めない

-- ランキングを取得する
SELECT user_id,score,ranking FROM t WHERE user_id=123;  -- user_id=123 のスコアとランキングを取得

-- ユーザーの周辺のランキングを取得する
SELECT ranking_set_view("t", "user_id=123", 5);  -- SELECT の返す結果を user_id=123 の順位周辺5件に限定
SELECT user_id,score,ranking FROM t WHERE user_id=123 ORDER BY ranking;
SELECT ranking_reset_view();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment