自我加入一张桌子

use*_*961 3 php codeigniter

我正在尝试运行一个查询,从users表中选择所有用户并加入自己,因为我想选择创建用户的用户.出于某种原因,我在创建者中获得了与first_name和last_name相同的值,因为同一个用户不一定是真的.

user_Id, username, first_name, last_name, creator_id

1, ksmith, Kevin, Smith, 1
2, wscott, Will, Scott, 1
3, sjones, Steve, Jones, 1
4, twilliams, Tom, Williams, 4
Run Code Online (Sandbox Code Playgroud)
public function get_with_creator()
{
    $this->db->select('users.user_id');
    $this->db->select('users.username');
    $this->db->select('users.first_name');
    $this->db->select('users.last_name');
    $this->db->select('users.created_at');
    $this->db->select('users.updated_at');
    $this->db->select("CONCAT(creator.first_name, ' ', creator.last_name) AS creator_name", FALSE); 
    $this->db->from($this->_table); 
    $this->db->join('users AS creator', 'users.user_id = creator.user_id', 'inner');
    return $this->db->get()->result();
}
Run Code Online (Sandbox Code Playgroud)

Roc*_*mat 6

您正在加入表格users.user_id = creator.user_id.因此,它为每个字段返回相同的名称,因为您要加入同一行.

你需要加入users.creator_id = creator.user_id.

演示:http://sqlfiddle.com/#!2/e1309/2