2014-07-04 24 views
0

SQL結果對數據庫表我如何巢加入

Macro Table: 
ID | title | description 

Micro Table: 
ID | title | description | macro_id 

macro_id在「微表」相匹配的「宏表」的ID。我有很多Micros到一個Maco。

我想寫一個sql語句,會給我這樣的結果在PHP中。

[ 
    { 
    ID : 3, title : "some title", description : "some desc", micros : [ 
    { 
     ID : some number, 
     title : "some title", 
     description : "some description", 
     macro_id : 3 
    } 
    ] 
    } 
] 

對象的數組,其中每個對象是從宏觀表,然後每個宏對象中「微」對象與該特定宏去基於所述匹配的「macro_id」 ID的數組在宏表

微表和「ID」我試着做各種連接

SELECT * FROM macros JOIN micros ON macros.macro_id=micros.micro_id 

但也只是回到它在一排,而不是嵌套它。

編輯:這就是我正在做的(它在codeigniter),它給了我正在尋找的結果。這似乎只是在get_all_macros低效

$this->load->model('macros_model','',true); 
    $this->load->model('micros_model', '', true); 
    $all_macros = $this->macros_model->get_all_macros(); 

    $all_lessons = array(); 
    foreach($all_macros as $macro){ 
     $micros = $this->micros_model->get_all_micros_for_macro($macro['macro_id']); 
     $macro['micros'] = $micros; 
     array_push($all_lessons, $macro); 

    } 

的SQL查詢和get_all_micros_for_macro只是SELECT * FROM宏,和SELECT * FROM微WHERE macro_id = $ macro_id

+1

您需要更清楚地瞭解您對查詢的期望輸出。 –

+0

@juergend更新,使其更清楚 – Bill

+0

我的意思是:由於SQL查詢不返回對象,但只有行,它會更好地添加預期的sql結果,而不是讀取和處理查詢後的PHP輸出。 –

回答

0

下面的例子可能是有益的(未測試雖然) ...

$query = ' 
      SELECT 
       macroTable.ID as macroID, 
       macroTable.Title as macroTitle, 
       macroTable.Description as macroDescription, 
       microTable.ID as microID, 
       microTable.ID as microTitle, 
       microTable.ID as microDescription 
      FROM 
       macroTable 
       INNER JOIN microTable ON macroTable.ID = microTable.macro_id 
      ORDER BY 
       macroID 
     '; 

$resultArray = executeQuery($query); 

if ($resultArray){ 

    $nestedResults = array(); 

    $foreach ($resultArray as $row){ 

     $macroId = $row['macroID']; 
     if (isset($nestedResults)){ 
      $nestedResults[$macroId]['micros'][] = array(
                  'microID' => $row['microID'], 
                  'microTitle' => $row['microTitle'], 
                  'microDescription' => $row['microDescription'], 
                 ); 
     } else { 
      $nestedResults[$macroId] = array(
               'macroTitle' => $row['macroTitle'], 
               'macroDescription' => $row['macroDescription'], 
               'micros' => array() 
              ); 
     } 
    } 

}