Reputation: 2967
I have a function in my model of my codeigniter application that returns a list of rows in descending order of points. This is done to get the rows with the hihgest points.
public function top_points()
{
$this->db->order_by('points', 'desc');
$query=$this->db->get('player', 50);
$data = $query->result_array();
return $data;
}
This work fine in returning the data for the highest 50 points.
However I would like to find the position/rank of a particular player in the Player
table which I am querying. I would like to a specific player by an id
.
public function get_player_rank($player_id)
{
$this->db->where('player_id', $palyer_id);
$this->db->order_by('points', 'desc');
$query=$this->db->get('player');
$data = $query->result_array();
return $data;
}
I would like to use something like this to get the position of a player specified by his $id. Like a ranking in terms of his points earned.
How do i get this?
Upvotes: 1
Views: 1726
Reputation: 6344
TRY
$sql = "
SET @rownum=0;
SELECT player_id, rank
FROM (
SELECT player_id, @rownum := @rownum +1 AS rank FROM `player`
ORDER BY `points` DESC
) AS D
WHERE D.player_id=?";
$result = $this->db->query($sql,array($palyer_id))->row_array();
OR you could try
$sql = "
SELECT player_id, rank
FROM (
SELECT player_id, @rownum := @rownum +1 AS rank
FROM `player` , (SELECT @rownum :=0 ) r
ORDER BY `points` DESC
) AS D
WHERE D.player_id=?";
$result = $this->db->query($sql,array($palyer_id))->row_array();
Upvotes: 1