将 2 个查询合二为一

Posted

技术标签:

【中文标题】将 2 个查询合二为一【英文标题】:Combining 2 queries into one 【发布时间】:2013-02-09 23:38:06 【问题描述】:

我有这两个问题:

$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】:

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

$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 = ?
       )";

【讨论】:

我解释得很糟糕。使用您发布的完整查询编辑了我的帖子。它没有给我正确的结果。它只给我 3 分,而实际上它应该给 -174 和位置 0。希望编辑后的帖子有所帮助:-/

以上是关于将 2 个查询合二为一的主要内容,如果未能解决你的问题,请参考以下文章

以下 7 个更新查询的 SQL 优化。同一张桌子。合二为一?

SQL 脚本帮助,将两个查询合二为一

如何将这两个查询组合成一个查询?

将两个查询合二为一

如何在 SQL 中组合两个查询? (子查询)

如何将两个 sql 查询合二为一? [复制]