• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multiple db join on same table

[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:

$this->db->select('*, news.id as news_id, news.created as created_on');
$this->db->join('users', 'users.id = news.author and users.id = news.modified_by', 'left');

If you could help me, that would be great. Thanks!

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.
$this->db->join('users', 'users.id = news.author', 'left');
$this->db->join('users modified_user', 'modified_user.id=news.modified_by', 'left')

Optionally, you may also have to change the select to choose the name of each person manually.
$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');

[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?

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....

$this->db->select("topics.*, topic_creater.username as creater_name, topic_updater.username as updater_name")
->join("users topic_creater", "topics.topic_userid=topic_creator.user_id")
->join("users topic_updater", "topics.topic_modified_userid=topic_updater.user_id")

Please note that I join on the same "users" table 2 times, but aliased it differently for selecting theirs data.

[eluser]Wonder Woman[/eluser]
Ah I see, sorry I didn't realise, I've not used
join('users modified_user'...
to change the table name for the query.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.