2017-09-26 29 views
0

假設我有2個表:如何將一對多連接查詢的結果減少到每個「一個」的標誌對象?

Applicants: 
- id 
- full_name 
- address 

Educations: 
- id 
- applicant_id 
- institute 
- address 

後,我做了一個內部聯接,我想通過一個模板的數據環路。但首先,我想將申請人的所有教育記錄轉換爲數組並附加到申請人記錄中。

applicant_a: 
- id 
- full_name 
- address 
- educations: [ OBJECTS HERE ] 

這樣做的方法是什麼?我可以通過SQL在數據庫端執行嗎?或者我必須在PHP端做到這一點?

+0

有趣的問題。我相信你必須做2個查詢,除非你想加入並在結果的每一行都有額外的申請人數據。 –

+0

在php中更容易。循環,直到申請人變更時有兩個數組,然後將教育數組保存到申請人。 (當然你需要按照每個申請人的sql進行排序) – Jeff

回答

1

這是一個簡單的草案,我會如何做你的情況。
我不是說這是最好的,甚至唯一的的方式來做到這一點。
這個具體沒有測試,雖然我以前經常使用這種邏輯。
請注意,這只是關於這裏的邏輯....但這應該給你你想要的!

$applicants = array(); 
$old_applicant_id=null; 

while ($row=$db->fetch()) { 

    // new applicant 
    if($row['applicant_id']!=$old_applicant_id) { 
     // save the education to the old one - if there is one 
     if(isset($applicant)) { 
      $applicant['education'] = $educations; 
      $applicants[] = $applicant; 
     } 
     // then (and in first round) 
     $applicant = array(); 
     $applicant['fullName'] = $row['fullName']; 
     // repeat for other values of applicant 

     $educations = array(); // initialize educations 
     $education = array(); 
     $education['id'] = $row['edu_id']; 
     // repeat for institute, etc 
     $educations[] = $education; 
    } else { 
     // already existing applicant, so only add education 
     $education = array(); 
     $education['id'] = $row['edu_id']; 
     // repeat for institute, etc 
     $educations[] = $education; 
    } 
    // set old applicant 
    $old_applicant_id = $row['applicant_id']; 
} 
// finally you have to save the last one to the array 
$applicant['education'] = $educations; 
$applicants[] = $applicant; 

另一種方法是將兩個單獨的查詢合併爲兩個循環。

This question of mine有關。我在問這兩個版本的差距。可能很有趣。

0

MySQL不返回數組,所以這種事通常最好在客戶端代碼中完成(在這種情況下是PHP)。

但是,如果你只是想將教育連接成某種類型的字符串,你可能需要查看GROUP_CONCAT集合函數。

相關問題