對不起,提前大量查詢。我一直在努力,不能爲我的生活得到這個查詢工作。當兩個登錄用戶互相對戰時,這會爲兩位用戶增加贏家和輸家。 (這是石頭剪刀)。我可以讓它爲單個用戶工作,但是當我嘗試收集用戶的「統計表」時,我得到了重複。這個查詢可能嗎?
這裏是我的簡稱換了 - 清酒的,簡潔模式
create table rps_user (
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(255),
PRIMARY KEY (user_id),
UNIQUE (username)
);
CREATE TABLE rps_session (
session_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
player1_user_id INT UNSIGNED DEFAULT NULL,
player2_user_id INT UNSIGNED DEFAULT NULL,
connected BOOLEAN DEFAULT 0,
PRIMARY KEY (session_id)
);
CREATE TABLE rps_game (
game_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
game_number INT UNSIGNED DEFAULT NULL,
session_id INT UNSIGNED NOT NULL,
player1_choice ENUM('ROCK','PAPER','SCISSORS') DEFAULT NULL,
player2_choice ENUM('ROCK','PAPER','SCISSORS') DEFAULT NULL,
PRIMARY KEY (game_id)
);
這裏是我的查詢工作
SELECT IF((player1_choice + 1) % 3 + 1 = player2_choice + 0 AND player1_user_id = rps_user.user_id OR
(player2_choice + 1) % 3 + 1 = player1_choice + 0 AND player2_user_id = rps_user.user_id, 1, 0) AS win,
IF(player1_choice = player2_choice, 1, 0) as tie,
IF(player1_choice % 3 + 1 = player2_choice + 0 AND player1_user_id = rps_user.user_id OR
player2_choice % 3 + 1 = player1_choice + 0 AND player2_user_id = rps_user.user_id, 1, 0) AS loss
FROM rps_game INNER JOIN rps_session USING (session_id)
INNER JOIN rps_user ON rps_session.player1_user_id = rps_user.user_id OR rps_session.player2_user_id = rps_user.user_id
WHERE player1_choice IS NOT NULL AND player2_choice IS NOT NULL and rps_user.user_id = ?
並且不
的一個SELECT username, SUM(IF((player1_choice + 1) % 3 + 1 = player2_choice + 0 AND player1_user_id = rps_user.user_id OR
(player2_choice + 1) % 3 + 1 = player1_choice + 0 AND player2_user_id = rps_user.user_id, 1, 0)) AS wins,
SUM(IF(player1_choice = player2_choice, 1, 0)) AS ties,
SUM(IF(player1_choice % 3 + 1 = player2_choice + 0 AND player1_user_id = rps_user.user_id OR
player2_choice % 3 + 1 = player1_choice + 0 AND player2_user_id = rps_user.user_id, 1, 0)) AS losses
FROM rps_game INNER JOIN rps_session USING (session_id)
INNER JOIN rps_user ON rps_session.player1_user_id = rps_user.user_id OR rps_session.player2_user_id = rps_user.user_id
WHERE player1_choice IS NOT NULL AND player2_choice IS NOT NULL
GROUP BY user_id ORDER BY wins DESC
祝你好運,謝謝你!
您是否考慮過使用命令式編程語言? – Borealid 2010-08-10 00:37:32
我有,並最終(更快,沒有解決方案)會。這真的是懶惰變成sql練習的結果。 – uzrbin 2010-08-10 23:45:54