组合多个MySQL JOIN查询

时间:2013-02-22 19:03:07

标签: php mysql sql join left-join

我有这个查询,其中包含用户注册的类的分配ID。

$sql = $db->prepare("SELECT assignments.*, enrollments.course_id, enrollments.student_id
                        FROM assignments
                        LEFT JOIN enrollments
                        ON assignments.course_id = enrollments.course_id
                        LEFT JOIN completed
                        ON assignments.id != completed.assignment_id
                        WHERE enrollments.student_id = ?
                        ORDER BY assignments.id DESC LIMIT 10
                        ");

$sql->execute(array($login_id));

while($row = $sql->fetch())
        {
                echo $row['id'];
        }

在我看到作业是否已标记为已完成的情况下,进行另一项检查的最佳方法是什么?

这意味着它还需要检查“已完成”表,并确保没有行,其中$ login_id和assignment.id一起出现在所选的任何分配中。

这是我现在要查找已登录用户的已完成作业ID的查询。

$sqlcomplete = $db->prepare("SELECT * FROM completed
INNER JOIN students ON completed.student_id = students.id
WHERE completed.student_id = ?
");

$sqlcomplete->execute(array($login_id));

while($row = $sqlcomplete->fetch(PDO::FETCH_ASSOC))
{
echo "<li>You have completed assignment with ID ".$row['assignment_id']."</li>";
}

我试图做一个更复杂的JOIN,但我似乎无法弄明白。我还考虑通过单独查询该数据库创建一个用户已完成的分配ID数组,并将该ID转入while检查,但我觉得这不是最好或最有效的解决方案。

1 个答案:

答案 0 :(得分:2)

您可以使用LEFT JOIN,当completed.assignment_id IS NULL时,这意味着已完成的表格中没有返回匹配项。

SELECT assignments.*, enrollments.course_id, enrollments.student_id
FROM assignments
 LEFT JOIN enrollments ON assignments.course_id = enrollments.course_id
 LEFT JOIN completed ON assignments.id = completed.assignment_id
WHERE enrollments.student_id = ?
AND completed.assignment_id IS NULL
ORDER BY assignments.id DESC LIMIT 10