2017-04-21 79 views
0

我想查询一对多的关系笨合并成一条记录与SQL一对多的关系

如:

Table A:      Table B: 

id | country_name    id | name | table_A_id 

1 | Usa      1 | kerry | 1 

2 | Australia    2 | jerry | 1 

           3 | tommy | 2 

           4 | cherry | 2 

我的目的是查询结果进行合并一行记录

如:结果列表:

1 Record   2 Record 
Usa    Australia 
kerry    tommy 
jeryy    cherry 

目前,我使用Codeignter framewo rk和sql的初学者,请不要介意我家伙。

$this->db->select('*') 
>from("table A") 
->join("table B", "table.A.id = table_A_id"); 
$query = $this->db->get(); 
if($query->num_rows() > 0) {  
    return $query->result(); 
} 

我的观点

<?php foreach($posts as $post) { 
    echo $post->country_name; 
    echo $post->name; 
} ?> 

但是,它给了我4个记录。

1 Record   2 Record 
Usa    Usa 
kerry    jerry 

3 Record   4 Record 
Australia   Australia 
tommy    cherry 

谢谢你们提前帮助我。

回答

0

这里是你错过了什么

$this->db->select('*') 
>from("table A") 
->join("table B", "table.A.id = table_A_id"); 
$query = $this->db->get(); 
if($query->num_rows() > 0) {  
    return $query->result(); 
} 

它应该是

->join("table B", 'B.table_A_id=A.id'); 

希望这有意义

B选项

$this->db->join('table B','B.table_A_id=A.id','INNER'); 
$query = $this->db->get('table A'); 
+0

谢谢回答,但它仍然不正确。 –

+0

我已更新我的评论对不起选项B –

+0

这是从你工作结束? –

0

尝试这个

SELECT country, group_concat(name) FROM city c INNER JOIN employee e 
ON c.id = e.city_id group by c.id 

输出

('USA '  , 'jerry ,kerry'), 
('Australia', 'cherry ,tommy'); 
+0

我var_dump得到这些结果,但我不能通过它进入视图循环。 –

0

我的解决方法发现不使用内部联接:

public function mergeRecord() { 
    $array_store = array(); 
    foreach($this->one() as $row) { 
     $child = $this->many($row['id']); 
     if($child) {   
      $return = array_merge(array("parent" => $row), array("child" =>$child));    
      array_push($array_store, $return);            
     } 
    } 
    return $array_store;     
} 

public function one() { 
    $query = $this->db->select("*") 
    ->get("table A") 
    ->result_array(); 
    return $query; 
} 

public function many($id) { 
    $query = $this->db->select("id, name")   
    ->where("table_A_id", $id) 
    ->get("table B") 
    ->result_array(); 
    return $query; 
}