-1

我有一个如下的 MySQL 查询;我想在一个有 180 万条记录的表中为每个 600 条记录范围选择顶部记录。到目前为止,我必须循环 3,000 次才能完成此操作,这不是一个有效的解决方案。

数据库模式;

 Table: bet_perm_13predict
 id     bet_id      perm_id     avg_odd     avg_odd2    avg_odd3
 1      23          1           43.29       28.82       28.82
 2      23          2           42.86       28.59       28.59
 3      23          3           43.13       28.73       28.73


 Table: bet_permute_13games
 perm_id    perm_code
 1      0000000000000
 2      0000000000001
 3      0000000000002
 4      0000000000010

PHP 中的示例 MySQL 查询

$totRange   = 0; //Used as starting point in rang
$range      = 600; //Used as range
$stop       = 0;//Used as endPoint of range

while($totRange < 1800000){
    $stop   = $totRange+$range;

    $sql = "SELECT (tb1.avg_odd2 + tb1.avg_odd3) AS totAvg_odd ,
    tb1.perm_id , tb1.avg_odd, tb1.avg_odd2, tb1.avg_odd3, tb2.perm_code 
    FROM bet_perm_13predict tb1 
    INNER JOIN bet_permute_13games tb2 ON tb2.perm_id = tb1.perm_id
    WHERE tb1.bet_id = '$bet_id' && tb1.perm_id 
    BETWEEN $startRange AND $stop ORDER BY totAvg_odd ASC LIMIT 1"

    $q1    = $this->db->query($sql);
    $totRange = $stop;
}

换句话说,我想选择一个代表整个表的数据样本,该样本不是随机的,而是使用 600 范围内的顶部记录预定义的。到目前为止,我不知道如何继续。没有关于此主题的明确在线材料。

4

2 回答 2

1

您可以使用整数除法来创建组。

演示

SELECT ID, ID DIV 600 as grp
FROM Table1

然后找到每组的最大值。这里有一些选项

获取每组分组 SQL 结果的最大值记录

于 2018-09-24T20:12:57.550 回答
0

对于那些可能遇到同样问题的人,这就是我解决它的方法。我使用了@Juan Carlos 的建议,并添加了一种方法来使用子查询选择组的最高记录。

SELECT * FROM 
         (SELECT * , perm_id DIV $limit as grp , (avg_odd2 + avg_odd3) AS totAvg_odd 
           FROM bet_perm_13predict WHERE bet_id = '$bet_id'  ORDER BY grp ASC ) tb1
INNER JOIN bet_permute_13games tb2 ON tb2.perm_id = tb1.perm_id
INNER JOIN bet_entry tb3 ON tb3.bet_id = tb1.bet_id
WHERE tb1.avg_odd2 < (SELECT AVG(avg_odd2) FROM bet_perm_13predict WHERE bet_id = '$bet_id' )
                     && tb1.avg_odd3 < (SELECT AVG(avg_odd3) FROM bet_perm_13predict WHERE bet_id = '$bet_id' )
GROUP BY grp ORDER BY totAvg_odd ASC
LIMIT 100
于 2018-09-26T15:04:36.673 回答