我有3個表:的MySQL MAX()GROUP BY 3個表
CREATE TABLE IF NOT EXISTS sportsman (
sportsman_id int NOT NULL AUTO_INCREMENT,
sportsman_name varchar(255) NOT NULL,
PRIMARY KEY (sportsman_id)
);
CREATE TABLE IF NOT EXISTS competition (
competition_id int NOT NULL AUTO_INCREMENT,
competition_name varchar(255) NOT NULL,
PRIMARY KEY (competition_id)
);
CREATE TABLE IF NOT EXISTS results (
competition_id int,
sportsman_id int,
result float,
FOREIGN KEY (sportsman_id) REFERENCES sportsman(sportsman_id),
FOREIGN KEY (competition_id) REFERENCES competition(competition_id)
);
這裏是樣本數據:
INSERT INTO `sportsman` (`sportsman_name`) VALUES ('sportsman1');
INSERT INTO `sportsman` (`sportsman_name`) VALUES ('sportsman2');
INSERT INTO `competition` (`competition_name`) VALUES ('competition1');
INSERT INTO `competition` (`competition_name`) VALUES ('competition2');
INSERT INTO `results` (`competition_id`, `sportsman_id`, `result`) VALUES ('1', '1', '20');
INSERT INTO `results` (`competition_id`, `sportsman_id`, `result`) VALUES ('1', '2', '25');
INSERT INTO `results` (`competition_id`, `sportsman_id`, `result`) VALUES ('2', '1', '18');
INSERT INTO `results` (`competition_id`, `sportsman_id`, `result`) VALUES ('2', '2', '23');
我需要得到competition_name,最大的結果,sportsman_name。
我的查詢是:
SELECT
c.`competition_name`,
MAX(r.`result`),
s.`sportsman_name`
FROM `competition` c
INNER JOIN `results` r ON c.`competition_id` = r.`competition_id`
INNER JOIN `sportsman` s ON s.`sportsman_id` = r.`sportsman_id`
GROUP BY c.`competition_name`;
它按competition_name,發現最大的結果。但它選擇了第一個sportsman_name。
有什麼建議嗎?
你想什麼要發生的,而不是 – Strawberry
可能的複製[取它具有最高值的列行(https://stackoverflow.com/questions/121387/fetch-該行具有最大值的列) – Uueerdo