2016-06-28 58 views
0

用戶的等級我有這樣的一個表:如何執行CI中自定義查詢 - 在得分表

id  user_id  score 

1  16433  20 
2  16433  10 
3  14621  12 
4  47899  10 
5  13220  30 
6  14621  15 

我的表名是game_scores。 現在,我想在得分表中獲得用戶(或它的極限8個用戶)的排名:

$query = $this->db->query(" 

         SET @rnk=0; SET @rank=0; SET @curscore=0; 
         SELECT score,id,rank FROM 
         (
          SELECT AA.*,BB.ID, 
          (@rnk:[email protected]+1) rnk, 
          (@rank:=IF(@curscore=score,@rank,@rnk)) rank, 
          (@curscore:=score) newscore 
          FROM 
          (
           SELECT * FROM 
           (SELECT COUNT(1) scorecount,score 
           FROM game_scores GROUP BY score 
          ) AAA 
          ORDER BY score DESC 
         ) AA LEFT JOIN game_scores BB USING (score)) A; 

         "); 

return $query; 

但它返回false。

我把這個代碼從這個鏈接:

https://dba.stackexchange.com/questions/13703/get-the-rank-of-a-user-in-a-score-table

+0

請將您的預期輸出發佈到給定的輸入集 – 1000111

+0

'vardump($ query);'是'bool(false)' –

回答

1

你可以使用這樣的查詢:

SELECT 
@rank := (@rank+1) AS rank, 
sc.user_id , sc.score 
FROM 
(
    SELECT user_id , max(score) AS score 
    FROM myscore 
    GROUP BY user_id 
    ORDER BY score DESC 
    LIMIT 8 
) AS sc 
CROSS JOIN (SELECT @rank := 0) AS param; 

樣品

MariaDB [yourschema]> select * from myscore; 
+----+---------+-------+ 
| id | user_id | score | 
+----+---------+-------+ 
| 1 | 16433 | 20 | 
| 2 | 16433 | 10 | 
| 3 | 14621 | 12 | 
| 4 | 47899 | 10 | 
| 5 | 13220 | 30 | 
| 6 | 14621 | 15 | 
| 7 | 47891 | 10 | 
| 8 | 13222 | 30 | 
| 9 | 14623 | 15 | 
+----+---------+-------+ 
9 rows in set (0.00 sec) 

MariaDB [yourschema]> SELECT 
    -> @rank := (@rank+1) AS rank, 
    -> sc.user_id , sc.score 
    -> FROM 
    -> (
    -> SELECT user_id , max(score) AS score 
    -> FROM myscore 
    -> GROUP BY user_id 
    -> ORDER BY score DESC 
    -> LIMIT 8 
    ->) AS sc 
    -> CROSS JOIN (SELECT @rank := 0) AS param; 
+------+---------+-------+ 
| rank | user_id | score | 
+------+---------+-------+ 
| 1 | 13220 | 30 | 
| 2 | 13222 | 30 | 
| 3 | 16433 | 20 | 
| 4 | 14621 | 15 | 
| 5 | 14623 | 15 | 
| 6 | 47899 | 10 | 
| 7 | 47891 | 10 | 
+------+---------+-------+ 
7 rows in set (0.00 sec) 

MariaDB [yourschema]> 
+0

它不會返回任何值。 –

+0

@ S.M_Emamian - 對不起,我不能說出了什麼問題。我沒有任何有關空白結果的信息 –

0

你需要

return $query->result();