Codeigniter SQL查询在两个不同的列上连接

时间:2015-04-06 14:44:03

标签: php mysql sql codeigniter

我有以下表格:

用户:

+----+-------+-------+
| ID | fname | lname |
+----+-------+-------+
| 1  | Joe   | Doe   |
+----+-------+-------+
| 2  | Jane  | Doet  |
+----+-------+-------+

产品:

+----+------+------------+------------+
| ID | name | created_by | updated_by | //created_by and updated_by are user Ids
+----+------+------------+------------+
| 1  | some | 1          | 1          |
+----+------+------------+------------+
| 2  | some | 1          | 2          |
+----+------+------------+------------+
| 3  | some | 2          | 2          |
+----+------+------------+------------+
| 4  | some | 2          | 1          |
+----+------+------------+------------+

我想创建一个查询,输出下表:

+--------------+------------+------------+
| Product Name | Created By | Updated By |
+--------------+------------+------------+
| Some         | Jane Doet  | Joe Doe    |
+--------------+------------+------------+

到目前为止,我正在以这种方式使用Join

public function getAll() {
    $this->db->select('products.* , users.fname, users.lname');
    $this->db->from('products');
    $this->db->join('users', 'users.id = products.updated_by', 'left');
    $q = $this->db->get();
    return $q->result();
}

产生以下内容:

SELECT products.*, users.fname, users.lname 
FROM `products`
LEFT JOIN users ON users.id=products.updated_by

这样可以获取updated_by用户信息,但如果我同时需要createdupdated用户信息,我该如何进行查询呢?

2 个答案:

答案 0 :(得分:1)

我是codeigniter的残疾人,但如果我理解您的要求是正确的,那么以下内容可能会有所帮助。

public function getAll() {
  $selqry = 'p.* , u.fname as fname_ub, u.lname as lname_ub'  
  $selqry .= ', c.fname as fname_cb, c.lname as lname_cb'  

  $this->db->select( $selqry );
  $this->db->from('products as p');
  $this->db->join('users u', 'u.id = p.updated_by', 'left');

  $this->db->join('users c', 'c.id = p.created_by', 'left');

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

  return $q->result();
}

上面的代码应该产生以下SQL语句:

SELECT 
       p.*, u.fname as fname_ub, u.lname as lname_ub
       ,    c.fname as fname_cb, c.lname as lname_cb
FROM `products` as p
LEFT JOIN users u ON u.id=p.updated_by
LEFT JOIN users c ON c.id=p.created_by

答案 1 :(得分:1)

是的,这项工作对我来说非常有用

在我的控制器中

public function out()
    {
          $selqry = 'p.* , u.items as REAL'  ;
          $selqry .= ', c.items as ITEM'  ;
          $this->db->select( $selqry );
          $this->db->from('outgoing as p');
          $this->db->join('financial_items u', 'u.id = p.item_id_real', 'left');
          $this->db->join('financial_items c', 'c.id = p.item_id', 'left');
          $query = $this->db->get();
          $data = $query->result();
          echo json_encode($data);

    }