如何在单个查询中执行多个选择查询并仍然检索值

时间:2013-09-09 01:07:29

标签: php mysql sql performance

所以我的php脚本中有很多这样的东西:

//get current values to add to new ones
    $sql = "SELECT `pageViews` FROM $table WHERE `appName` = '$appName'";
    $result = mysql_query($sql);
    if (!$result) {
     die("Invalid query: " .mysql_error());
    }
    $totalPoints += mysql_result($result, 0, 0);


    //get current values to add to new ones
    $sql = "SELECT `appTime` FROM $table WHERE `appName` = '$appName'";
    $result = mysql_query($sql);
    if (!$result) {
     die("Invalid query: " .mysql_error());
    }
    $appRunTime += mysql_result($result, 0, 0);

    //get current values to add to new ones
    $sql = "SELECT `soundsPlayed` FROM $table WHERE `appName` = '$appName'";
    $result = mysql_query($sql);
    if (!$result) {
     die("Invalid query: " .mysql_error());
    }
    $lifesLost += mysql_result($result, 0, 0);

是否可以将所有这些查询合并为一个并仍然检索每个单独的信息,即将它们设置为变量?

感谢。

1 个答案:

答案 0 :(得分:1)

你在找这样的东西吗?

$sql = "SELECT pageViews, appTime, soundsPlayed 
          FROM $table 
         WHERE appName = '$appName'";

$result = mysql_query($sql);
if (!$result) {
 die("Invalid query: " .mysql_error());
}
if ($row = mysql_fetch_assoc($result)) {
    $totalPoints += $row['pageViews'];
    $appRunTime  += $row['appTime'];
    $lifesLost   += $row['soundsPlayed'];
}

旁注:而不是插入查询字符串,使用 prepared statements mysqli_*PDO