将每个ID的结果金额限制为x

时间:2013-07-18 12:03:34

标签: mysql sql

我试图在MYSQL中做这样的事情,但是没有通过PHP foreach多次查询(在我的情况下是50次)。

foreach($this->map_ids as $key => $val) {
    $this->db->query("SELECT scores.profile_number, scores.score  FROM scores 
                    LEFT JOIN players ON scores.profile_number = players.profile_number
                    WHERE scores.map_id = {'$val'}
                    AND scores.profile_number IN (SELECT profile_number FROM players WHERE banned = 0) LIMIT 10");    
}

当我在没有LIMIT的情况下检索所有分数时,这就是它的外观。

profile             score   map_id
76561198026851335   2478    47455
76561198043770492   2480    47455
...                 ...     ...
76561198043899549   1340    47452
76561198048179892   1345    47452
...                 ...     ...

我只希望每个唯一的map_id有10个条目(分数)。

2 个答案:

答案 0 :(得分:2)

这很难做到,但我最终使用用户变量来完成这项工作,请查看以下演示。显然我的数据结构已经大大简化了,但它应该足以让你前进:

<强> SQL Fiddle example

对于任何可能对跳过演示感兴趣的人来说,这是一个SQL(我知道这很可怕)

SELECT *
FROM (
      SELECT profile_number, score, map_id
      FROM ( 
        SELECT 
          profile_number, score, map_id, 
          IF( @prev <> map_id, @rownum := 1, @rownum := @rownum+1 ) AS rank, 
          @prev := map_id
        FROM scores 
        JOIN (SELECT @rownum := NULL, @prev := 0) AS r 
        ORDER BY map_id
      ) AS tmp 
      WHERE tmp.rank <= 10 
      ) s
      JOIN players p
        ON s.profile_number = p.profile_number

基本上,正在发生的是这样的:
ORDER BY map_id
通过map_id对您的表进行排序,以便所有相同的组合在一起。

接下来,我们使用以下逻辑为每一行分配一个rownumber:
IF( @prev <> map_id, @rownum := 1, @rownum := @rownum+1 )
如果前一行的map_id不等于当前行的ID,则设置行号= 1,否则将rownumber增加1。

最后,只返回rownumber小于或等于10的行 WHERE tmp.rank <= 10

希望能让你更清楚一点。

答案 1 :(得分:0)

您可以使用limit directive.

SELECT * FROM `your_table` LIMIT 0, 10 

This will display the first 10 results from the database.

SELECT * FROM `your_table` LIMIT 0, 10 

这将显示记录6,7,8,9和10

相关问题