查询看起来不错,尽管您似乎错过了其中一列(假设您实际上需要使用 person.city):
select person.id, person.first_name, person.city, study.name from person
left join person_studies on person.id = person_studies.person_id
left join study on person_studies.study_id = study.id
where person.id=14;
代替:
select person.id, person.first_name, study.name from person
left join person_studies on person.id = person_studies.person_id
left join study on person_studies.study_id = study.id
where person.id=14;
至于结果,我不知道有什么方法可以直接将其格式化为您想要的格式。如果你不介意一点代码,你可以尝试获取你得到的结果并格式化它们。假设您使用的是 PDO(通常与 Zend 一起使用),它看起来像这样:
$statement = $db->query(<<query from above goes here>>);
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$personStudies = array();
foreach($result as $row)
{
$personId = $row['person.id'];
$studyName = $row['name'];
$personStudies[$personId]['first_name'] = $row['first_name'];
$personStudies[$personId]['study_names'][] = $studyName;
}
foreach($personStudies as $personId=>$person)
{
$formattedRow = array();
$formattedRow['person.id'] = $personId;
$formattedRow['first_name'] = $person['first_name'];
$formattedRow['study_names'] = $person['study_names'];
$formattedResults[] = $formattedRow;
}
并且$formattedResults
应该看起来就像你指定的那样。否则,您可以分两部分进行查询:
$statement = $db->query('SELECT person.first_name FROM person WHERE person.id=14 LIMIT 1');
$person = $statement->fetch(PDO::FETCH_ASSOC);
$name = $person['first_name'];
$statement = $db->query('SELECT study.name FROM person_studies, study WHERE person_studies.study_id = study.id AND person_studies.person_id=14'); // Same as a left join
$studyNames = $statement->fetch(PDO::FETCH_COLUMN, 0);
$formattedRow = array();
$formattedRow['person.id'] = 14;
$formattedRow['first_name'] = $name;
$formattedRow['study_names'] = $studyNames;
$formattedResults[] = $formattedRow;
这应该给出相同的结果。我没有测试过代码,但它应该接近你需要的。