如何修改此MySQL查询以查找排名?

时间:2013-09-03 08:37:10

标签: php mysql sql rank

我正在用PHP开发一个联盟应用程序。当我访问梯形图视图页面时,我有一个查询,从该梯子中选择所有小队并根据他们的经验(league_experience)命令他们。我想修改查询,以便找到当前小队的等级。

$query_squads = "
            SELECT
                s.squad_id AS squad_id, s.ladder_id, s.team_id AS team_id,
                x.experience_id, x.squad_id, SUM(x.value) as total_exp
            FROM league_squads AS s
            LEFT JOIN league_experience AS x ON (s.squad_id = x.squad_id)
            WHERE s.ladder_id = ".$ladder_id."
            GROUP BY s.squad_id, s.ladder_id, s.team_id, x.experience_id, x.squad_id
            ORDER BY total_exp DESC
            ";

这是我的表格

--
-- Table structure for table `league_experience`
--

CREATE TABLE IF NOT EXISTS `league_experience` (
  `experience_id` int(15) NOT NULL,
  `squad_id` int(15) NOT NULL,
  `value` int(15) NOT NULL,
  `date_earned` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `description` varchar(255) NOT NULL,
  PRIMARY KEY (`experience_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `league_experience`
--

INSERT INTO `league_experience` (`experience_id`, `squad_id`, `value`, `date_earned`, `description`) VALUES
(1, 1, 500, '2013-09-03 07:10:59', 'For being ballers.'),
(2, 2, 250, '2013-09-03 07:10:52', 'For being awesome.');

-- --------------------------------------------------------

--
-- Table structure for table `league_squads`
--

CREATE TABLE IF NOT EXISTS `league_squads` (
  `squad_id` int(15) NOT NULL AUTO_INCREMENT,
  `team_id` int(15) NOT NULL,
  `ladder_id` int(15) NOT NULL,
  `date_joined` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `status` tinyint(1) NOT NULL,
  `last_rank` tinyint(5) NOT NULL,
  PRIMARY KEY (`squad_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `league_squads`
--

INSERT INTO `league_squads` (`squad_id`, `team_id`, `ladder_id`, `date_joined`, `status`, `last_rank`) VALUES
(1, 1, 1, '2013-09-03 08:16:27', 0, 1),
(2, 2, 1, '2013-09-03 08:16:25', 0, 2);

1 个答案:

答案 0 :(得分:1)

SELECT
                s.squad_id AS squad_id, s.ladder_id, s.team_id AS team_id,
                x.experience_id, x.squad_id, SUM(x.value) as total_exp,
                @i:=@i+1 AS rank
            FROM league_squads AS s
            LEFT JOIN league_experience AS x ON (s.squad_id = x.squad_id),
            (SELECT @i:=0) AS foo
            WHERE s.ladder_id = 1
            GROUP BY s.squad_id, s.ladder_id, s.team_id, x.experience_id, x.squad_id
            ORDER BY total_exp DESC

<强> sample fiddle