将2个查询合并为一个

时间:2013-02-09 23:38:07

标签: php mysqli query-optimization

我有这两个查询:

$sql = "SELECT SUM(points) as userpoints FROM ".$prefix."_publicpoints
                        WHERE date BETWEEN ? AND ? AND fk_player_id = ?";

// Getting the users points into a variable to use in the next query
$userPoints;

$getuserplacement = "SELECT fk_player_id FROM ".$prefix."_publicpoints
                            WHERE date BETWEEN ? AND ?
                                GROUP BY fk_player_id
                            HAVING SUM(points) > $userPoints";

// After this I count the rows I get and put that into a variable and thats the users Rank
$userRank = $stmt->num_rows + 1;

这给了我这些数字:分数:-178位置:1891

然后我尝试了Ivan的例子:

    $sql= "SELECT fk_player_id FROM ".$prefix."_publicpoints
                        WHERE date BETWEEN ? AND ?
                            GROUP BY fk_player_id
                        HAVING SUM(points) > (
             SELECT SUM(points) as userpoints FROM ".$prefix."_publicpoints
                        WHERE date BETWEEN ? AND ? AND fk_player_id = ?
   )";

if($stmt->prepare($sql)){
    $stmt->bind_param('ssssi',$yearFrom,$yearTo,$yearFrom,$yearTo,$playerid);
    $stmt->execute();
    $stmt->store_result();
    $userMrank = $stmt->num_rows;
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    $stmt->bind_result($userPoints);
    $stmt->fetch();
}

这给了我这些数字:积分:3位置:0

是否可以将这两个查询合并为一个?

希望得到帮助: - )

1 个答案:

答案 0 :(得分:0)

我不知道我是否理解你,但是,你想要这个吗?

$sql= "SELECT fk_player_id FROM ".$prefix."_publicpoints
                            WHERE date BETWEEN '$year-01-01' AND '$year-12-31'
                                GROUP BY fk_player_id
                            HAVING SUM(points) > (
                 SELECT SUM(points) as userpoints FROM ".$prefix."_publicpoints
                            WHERE date BETWEEN ? AND ? AND fk_player_id = ?
       )";