在 codeigniter 中为两列选择加入

问题描述 投票:0回答:3

大家好;

Table 1
    id product_name location added_by updated_by added date
    1  LENOVO       St 23    2        1          2016-08-26

Table 2
id first_name last_name email
1  John       Doe       [email protected]
2  Peter      Smith     [email protected]

我想知道如何使用 codeigniter 查询选择数据以获得这样的结果

product_name location added_by    updated_by
LENOVO       St 23    Peter Smith John Doe

我试过加入但

added_by
列和
updated_by
列显示相同的数据。

mysql codeigniter codeigniter-3
3个回答
2
投票

您可以使用此查询来解决您的问题:

$this->db->select('t1.product_name,t1.location, CONCAT(t2_1.first_name, " ", t2_1.last_name) AS added_by, CONCAT(t2_2.first_name, " ", t2_2.last_name) AS updated_by'); 
$this->db->from('Table 1 t1');
$this->db->join('Table 2 t2_1', 't2_1.id = t1.added_by', 'left'); 
$this->db->join('Table 2 t2_2', 't2_2.id = t1.updated_by', 'left'); 
$query = $this->db->get();
return $query->result();

您可以根据查询中的表名更改表 1表 2


0
投票

这应该有效

$this->db->select('*')
  ->from('Table 1')
  ->join('Table 2', 'Table 2.id = Table 1.added_by', 'left')
  ->join('Table 2', 'Table 2.id = Table 1.updated_by', 'left');

$query = $this->db->get();

return $query->result();

让我知道它是否有效。


0
投票

您可以使用此查询来连接多列

$this->db->select('*')
->from('table_1')

->join('table_2', 'table_2.id = table_1.added_by AND table_2.id = table_1.updated_by', 'left');

$query = $this->db->get();

return $query->result();
© www.soinside.com 2019 - 2024. All rights reserved.