Question

I am developing a league application in PHP. When I visit the ladder view page, I have a query that selects all the squads from that ladder and orders them by their experience(league_experience). I want to modify the query so that it finds the rank of the current squad.

$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
            ";

Here's my tables

--
-- 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);
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top