如何使用连接嵌套sql结果

时间:2014-07-04 15:41:37

标签: php sql join

我必须使用DB Tables

Macro Table:
ID | title | description

Micro Table:
ID | title | description | macro_id

微表中的

macro_id"匹配"宏表"的ID。我有很多微软到一个Maco。

我试图编写一个sql语句,在PHP中给我一些这样的结果。

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

一个对象数组,其中每个对象来自宏表,然后在每个宏对象中有一个" micro"基于" macro_id"的匹配ID的特定宏的对象。在微表和" ID"在宏表中

我尝试过各种连接

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

但这只是将它返回到一行,而不是嵌套它。

编辑:这就是我正在做的事情(它在codeigniter中),它为我提供了我正在寻找的结果。这似乎效率低下

 $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);

    }

get_all_macros和get_all_micros_for_macro中的Sql查询只是SELECT * FROM宏,SELECT * FROM micro WHERE macro_id = $ macro_id

1 个答案:

答案 0 :(得分: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()
                                           );
       }
   }

}