![]() |
Multiple db join on same table - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20) +--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23) +--- Thread: Multiple db join on same table (/showthread.php?tid=42825) |
Multiple db join on same table - El Forum - 06-21-2011 [eluser]Wonder Woman[/eluser] Hi there, I have a news article database table which I have stored the id of a user in it twice, once for the author and secondly for who modified the article. So I need to do a multiple join but its not working properly. My code is: Code: $this->db->select('*, news.id as news_id, news.created as created_on'); If you could help me, that would be great. Thanks! Multiple db join on same table - El Forum - 06-21-2011 [eluser]aquary[/eluser] The joining condition is not good (for what the query is for). It'd works only if the news author and the modifier is the same person. You have to separate the join into two parts. Code: $this->db->join('users', 'users.id = news.author', 'left'); Optionally, you may also have to change the select to choose the name of each person manually. Code: $this->db->select('news.*, news.id as news_id, news.created as created_on, users.name as author_name, modifier_users.name as modifier_name'); Multiple db join on same table - El Forum - 06-21-2011 [eluser]Wonder Woman[/eluser] Thanks for your reply but they're not in separate tables, I have author and modified_by in the news table, which stores the id of a user which I want to retrieve from the users table. For example, an article might have been created by author whose id is 1 but later edited by a user whose id is 2...how do I amend my query to the db to get these two different users? Multiple db join on same table - El Forum - 06-21-2011 [eluser]aquary[/eluser] I understand that it's not in separate tables, but my answer was that "you have to join the users table 2 times". I also have that kind of query for my webboard topics & replies, which looks like.... Code: $this->db->select("topics.*, topic_creater.username as creater_name, topic_updater.username as updater_name") Please note that I join on the same "users" table 2 times, but aliased it differently for selecting theirs data. Multiple db join on same table - El Forum - 06-21-2011 [eluser]Wonder Woman[/eluser] Ah I see, sorry I didn't realise, I've not used Code: join('users modified_user'... |