我有一张候选人表和一张笔记表,每个候选人都有多个笔记。
我尝试运行SQL查询以通过ID(candID)获取特定候选人的详细信息以及与候选人匹配的备注。
我不太确定如何做到这一点,因为会有很多笔记返回。我需要做两个单独的查询吗?
这是我到目前为止所得到的但是它不完整(candID是候选人的id,candidateID是notes表中的相关id字段):
try {
$sql = 'SELECT Firstname, Lastname, candID, Email, note
FROM candidate RIGHT JOIN notes ON candID=candidateID WHERE candID='.$loadcandID.'';
$result = $pdo->query($sql);
}
catch (PDOException $e) {
$error = 'Error fetching candidate: ' . $e->getMessage();
include $errorpage;
exit();
}
$row = $result->fetch();
$cand = array(
'firstname' => $row['Firstname'],
'lastname' => $row['Lastname'],
'email' => $row['Email'],
);
答案 0 :(得分:1)
要正确执行JOIN,您必须在查询中具体 -
SELECT `candidate`.`Firstname` AS `first`, `candidate`.`Lastname` AS `last`, `candidate`.`candID` AS `id`, `candidate`.`Email` AS `email`, `notes`.`note` AS `note`
FROM `candidate`
LEFT JOIN `notes`
ON `candidate`.`candID` = `notes`.`candidateID`
WHERE `candID` = '1'