1

我有以下代码,想知道如何将其简化为一个 MYSQL 语句

$sql = "SELECT sesionID 
FROM  `juegos_sesiones` 
WHERE  `usuarioID` = ".$_SESSION['MM_UserID'];


$query = mysql_query($sql, $cnx) or die(mysql_error());
//$row_rsPaises = mysql_fetch_assoc($rsPaises);
$exercises = mysql_num_rows($query);

echo $exercises;

//find total points

while( $row = mysql_fetch_array($query)){

$sql2 = 'SELECT correct_answers FROM `juegos_sesiones_detalle`  WHERE  `sesionID`  = '.$row['sesionID'];


$query2 = mysql_query($sql2, $cnx) or die(mysql_error());
$details2 = mysql_fetch_assoc($query2);
$counter = $counter + $details2['correct_answers'];

}

echo '<br />'.$counter;
4

3 回答 3

1

您可以使用INNER JOIN as 编写单个查询:

SELECT correct_answers
FROM juegos_sesiones_detalle a
    INNER JOIN juegos_sesiones b
        ON a.sesionID = b.usuarioID;
于 2012-08-02T08:09:58.220 回答
1
SELECT sum(correct_answers) as total_correct_answers
FROM `juegos_sesiones_detalle` d
INNER JOIN  `juegos_sesiones` s on s.`sesionID` = d.`sesionID`
WHERE  `usuarioID` = $_SESSION['MM_UserID']

您可以在此处阅读有关联接的信息

于 2012-08-02T08:10:14.230 回答
0

试试这个 :

$sql = "SELECT correct_answers FROM `juegos_sesiones_detalle` jsd
        JOIN `juegos_sesiones` js
        ON jsd.sesionID = js.`sesionID`
        WHERE js.usuarioID = ".$_SESSION['MM_UserID'];
于 2012-08-02T08:13:04.137 回答