大家好,我的 mySQL 查询有问题。请查看我的表格和当前查询。
表“教员”
---------------------------------------------
id |firstname | lastname | subject_id|
---------------------------------------------
1 Juan Dela Cruz 1
2 Antonio Brigada 2
--------------------------------------------
表“主题”
---------------
id | name |
---------------
1 English
2 Math
3 Science
--------------
我当前的查询
public function instructor(){
global $database;
$sql = "SELECT instructors.firstname as firstname, instructors.lastname as lastname ";
$sql .= "FROM subjects ";
$sql .= "JOIN instructors ";
$sql .= "WHERE subjects.id = instructors.subject_id";
$result = $database->query($sql);
while($instructor = $database->fetch_array($result)){
if (isset($instructor['firstname']) && isset($instructor['lastname'])){
return $instructor['lastname'] . " " . $instructor['firstname'];
} else {
return "N/A";
}
}
}
结果:
English Juan Dela Cruz
Math Juan Dela Cruz
Science Juan Dela Cruz
编辑
当前的sql:
public function instructor(){
global $database;
$sql = "SELECT a.name, ";
$sql .= "COALESCE(CONCAT(b.firstname, ' ',b.lastname), 'N/A') as ins_name ";
$sql .= "FROM subjects a ";
$sql .= "LEFT JOIN instructors b ";
$sql .= "ON a.id = b.subject_id";
$result = $database->query($sql);
while($instructor = $database->fetch_array($result)){
return $instructor['ins_name'];
}
}
结果
English Juan Dela Cruz
Math Juan Dela Cruz
Science Juan Dela Cruz
它应该是什么:
English Juan Dela Cruz
Math Antonio Brigada
Science N/A
调用讲师()函数
<?php foreach($subjects as $subject): ;?>
<tr class="subject_list">
<td><?php echo $subject->name; ?></td> // This will show all subjects
<td><?php echo $subject->instructor(); ?></td> // This will show instructor foreach subjects
</tr>
<?php endforeach; ?>
我希望任何人都可以帮助我看到上面的结果。