0

我有一张桌子叫leaders. 在里面我有id, userid, bmid, reps, rounds, ts. 基本上,我需要将拥有最多rounds. 现在每次有人进入他们的repsrounds它是成对的,所以有人可能有 12 rounds13reps所以如果这是他们的最大值并且它在所有用户的前十名中,那么我需要提取该信息加上他们对应的reps. 我以为我有这个,但它实际上是从不同的行中拉出他们max rounds和他们的。max reps我所拥有的如下。

 SELECT max(l.rounds) as rounds, l.reps, m.name, l.userid 
 from leaders l 
 inner join members m on m.id = l.userid 
 where m.genre = 'male' and l.bmid  = 1 
 group by l.userid 
 order by  rounds desc,reps desc

joinmembers表中获取有关它们的一些信息。

4

1 回答 1

1

I guess you need a subquery to achieve this. Take a look at this:

How to select the first/least/max row per group in SQL

EDIT: Try this code: http://sqlfiddle.com/#!2/8bb81/3

CREATE TABLE `leaders` (
  `id` int(11) AUTO_INCREMENT,
  `userid` int(11),
  `rounds` int(11),
  `reps` int(11),
  PRIMARY KEY (`id`)
);

INSERT INTO `leaders` (userid, rounds, reps) VALUES
  (1, 5, 3), (1, 7, 2), (1, 7, 1), (1, 7, 8),
  (2, 7, 6), (2, 7, 9), (2, 4, 3),
  (3, 7, 2), (3, 3, 5),
  (4, 8, 9);

SELECT
  userid,
  MAX(rounds) AS max_rounds, (
    SELECT MIN(reps)
    FROM leaders l2
    WHERE l2.userid = l1.userid AND l2.rounds <> l1.rounds
  ) AS min_reps
FROM leaders l1
GROUP BY userid
ORDER BY max_rounds DESC, min_reps ASC;
于 2012-10-07T17:51:05.503 回答