Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self Joining A table

I'm trying to run a query that selects all of the users from the users table and joins itself because I would like to select who it was that created the user. For some reason I'm getting the same value I do for first_name and last_name in the creator as the same user which isn't true necessarily.

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
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();
}

1 Answers

You are joining the table(s) on users.user_id = creator.user_id. So, it returns the same name for each field, because you are joining the same row.

You need to join on users.creator_id = creator.user_id.

DEMO: http://sqlfiddle.com/#!2/e1309/2

like image 79
Rocket Hazmat Avatar answered May 01 '26 21:05

Rocket Hazmat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!