获取列的最小值和最大值以及所有行数据

时间:2017-02-26 20:59:55

标签: mysql group-by

CREATE TABLE users (
    users_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
    first_name VARCHAR( 20 ) NOT NULL,
    last_name VARCHAR( 40 ) NOT NULL,
    email VARCHAR( 60 ) NOT NULL,
    password CHAR( 40 ) NOT NULL,
    PRIMARY KEY ( users_id )
);

CREATE TABLE games (
    games_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
    locations_id MEDIUMINT UNSIGNED NOT NULL
    PRIMARY KEY (games_id )
);

CREATE TABLE games_users (
    users_id MEDIUMINT UNSIGNED NOT NULL,
    games_id MEDIUMINT UNSIGNED NOT NULL,
    score MEDIUMINT UNSIGNED NOT NULL,
    created DATETIME NOT NULL,
    last_updated DATETIME NOT NULL,
    PRIMARY KEY ( games_id, users_id )
);

使用上面的表格,每个游戏在2个用户之间,因此每个游戏的games_users有2行,每个玩家一个,获胜者将获得最高分(是的!)。

我想要每场比赛一行,我可以获得胜利和失败分数(使用下面的查询),但我还需要知道胜利者和失败者的身份。

SELECT 
    *, 
    min(score) as loser, 
    max(score) as winner 
FROM games
LEFT JOIN 
    games_members 
ON 
    games_members.games_id = games.games_id
GROUP BY 
    games_members.games_id

1 个答案:

答案 0 :(得分:1)

您可以使用自我加入 如果可以进行绘制,则可以更好地选择列的名称。

select
    gu1.games_id,
    winner.users_id 'id of the winner',
    gu1.score 'score of the winner',
    looser.users_id 'id of the looser'
    gu2.score 'score of the looser'
from games_users gu1
join games_users gu2 on gu1.games_id = gu2.games_id
join users winner on gu1.users_id = winner.users_is
join users looser on gu2.users_id = looser.users_is
where 1=1
and gu1.score >= gu2.score
and gu1.users_id != gu2.users_id
group by gu1.games_id
相关问题