我正在尝试left join
我的两张桌子在ON
之后只使用一个条件但是当我尝试添加第二个条件时我没有得到任何信息来自firstname
和lastname
列。我一直在寻找其他答案,从我看到的我做的一切都是正确的,所以我无法弄清楚为什么它不起作用..
这是我的尝试:
$stmt = 'SELECT courses.*, teachers.firstname, teachers.lastname ';
$stmt .= 'FROM courses LEFT JOIN teachers ON ';
$stmt .= 'courses.main_teacher = teachers.id AND courses.secondary_teacher = teachers.id';
$prep_stmt = $db->prepare($stmt);
$prep_stmt->execute();
while ($db_row = $prep_stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<tr>';
echo '<td class="info-cell">' . $db_row['name'] . '</td>';
echo '<td class="info-cell">' . $db_row['curriculum_url'] . '</td>';
echo '<td class="info-cell">' . $db_row['rating_criteria'] . '</td>';
echo '<td class="info-cell">' . $db_row['firstname'] . ' ' . $db_row['lastname'] . '</td>'; //Echoes main_teacher
echo '<td class="info-cell">' . $db_row['firstname'] . ' ' . $db_row['lastname'] . '</td>'; //Echoes secondary_teacher
echo '<td class="info-cell">' . $db_row['for_programme'] . '</td>';
echo '<td class="info-cell">
<button class="small-btns"><img src="../includes/img/edit.png"></button>
</td>';
echo '<td class="info-cell">
<button class="small-btns"><img src="../includes/img/delete.png"></button>
</td>';
echo '</tr>';
}
以下是它的输出:
正如您所看到的,当使用多个条件时,它不会返回教师表中的结果,为什么会这样?
修改:
我的数据库中的课程表:
我的数据库中的教师表:
我想要的结果:
答案 0 :(得分:3)
您似乎需要加入teachers
2次
select
c.*,
t1.firstname as main_teacher_firstname,
t1.lastname as main_teacher_lastname,
t2.firstname as secondary_teacher_firstname,
t2.lastname as secondary_teacher_lastname
from courses c
left join teacher t1 on t1.id = c.main_teacher
left join teacher t2 on t2.id = c.secondary_teacher