gpt4 book ai didi

php - 通过 subject_id 获取讲师姓名

转载 作者:行者123 更新时间:2023-11-29 05:32:47 29 4
gpt4 key购买 nike

大家好,我的 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

调用 instructor() 函数

<?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; ?>

希望大家帮我看看上面的结果

最佳答案

LEFT JOIN 是您所需要的

SELECT  a.name, 
COALESCE(CONCAT(b.firstName, ' ',b.LastName), 'N/A')
FROM subjects a
LEFT JOIN instructors b
ON a.ID = b.Subject_ID

关于php - 通过 subject_id 获取讲师姓名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13339634/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com