自连接返回错误/相反的结果?

时间:2019-03-28 13:16:23

标签: php codeigniter self-join

我需要使用Codeigniter使用下表中的“自我连接”。

+----------------------------+
| id | parent_id |  name     |
+----------------------------+
|  1 |  0        |  Ram      |
+----------------------------+
|  2 |  0        |  Alex     |
+----------------------------+ 
|  3 |  1        |  Sep      |
+----------------------------+ 
|  4 |  1        |  Mid      |
+----------------------------+ 
|  5 |  2        |  Seem     |
+----------------------------+
|  6 |  3        |  Julie    |
+----------------------------+

如何使用CodeIgniter查询获取如下所示的输出

+--------------------------------+
| id |  name     |  parent_name  |
+--------------------------------+
|  1 |  Ram      |     NULL      |
+--------------------------------+
|  2 |  Alex     |     NULL      |
+--------------------------------+
|  3 |  Sep      |     Ram       |
+--------------------------------+
|  4 |  Mid      |     Ram       |
+--------------------------------+
|  5 |  Seem     |     Alex      |
+--------------------------------+
|  6 |  Julie    |     Sep       |
+--------------------------------+

我已经使用别名选择了如下数据。

$this->db->select('p.id as p_id, p.name as p_name, p_parent.name as parent_name');
$this->db->from('Product as p');
$this->db->join('Product as p_parent', 'p_parent.parent_id = p.id   ','LEFT ');
$results = $this->db->get()->result_array();

我得到多个数组,但没有得到正确的结果。

Array ( 
 [0] => Array ( [p_id] => 1 [p_name] => ram [parent_name] => sep ) 
 [1] => Array ( [p_id] => 1 [p_name] => ram [parent_name] => Mid ) 
     . . . 
 [6] => Array ( [p_id] => 6 [p_name] => julie [parent_name] => ) ) 

为什么会这样?

1 个答案:

答案 0 :(得分:0)

尝试此查询以获取第二张表的输出

$this->db->select('p.id as id, p.name as name, p_parent.name as parent_name');
$this->db->from('Product as p');
$this->db->join('Product as p_parent', 'p.parent_id = p_parent.id  ','left');
$results = $this->db->get()->result_array();