我有一个mySQL表,其中包含来自多个用户的多个条目(由userid标识)。完整行包含用户ID,位置,种类和重量。我希望有一个排行榜,包含每个用户对于某个物种最重的重量和相应的位置。
我试过了:
SELECT userid, location, f_weight_i FROM eac.catches WHERE f_weight_i = (SELECT MAX(f_weight_i) FROM eac.catches) AND species='32' GROUP BY userid ORDER BY f_weight_i
但它没有返回任何行。
我也尝试了这个,它返回了整体最佳体重:
SELECT userid, location, f_weight_i FROM eac.catches WHERE f_weight_i = (SELECT MAX(f_weight_i) FROM eac.catches)
如何为每个物种获得每个物种的最佳重量?
答案 0 :(得分:0)
我没有时间创建测试表,但这应该让你接近。
SELECT userid, location, species, f_weight_i
FROM eac.catches INNER JOIN
(SELECT userid, species, MAX(f_weight_i) AS f_weight_i
FROM eac.catches GROUP BY userid, species) AS tmp
ON eac.catches.userid = tmp.userid
AND eac.catches.species = tmp.species
AND eac.catches.f_weight_i = tmp.f_weight_i;
答案 1 :(得分:0)
您可以使用内联视图(MySQL将其称为派生表)来获取给定物种的每个用户的最大f_weight_i。
然后将结果返回到表中以获得整行。
像这样:
SELECT c.userid
, c.species
, c.location
, c.f_weight_i
FROM eac.catches c
JOIN (
SELECT w.userid
, w.species
, MAX(w.f_weight_i) AS max_f_weight_i
FROM eac.catches w
WHERE w.species = '32'
GROUP BY w.userid, w.species
) m
ON m.max_f_weight_i = c.f_weight_id
AND m.userid = c.userid
AND m.species = c.species
ORDER BY c.f_weight_i DESC
要获取所有物种的结果,请从内联视图查询中删除WHERE子句(派生表m
)。