问题
I have two tables say Table1 and Table2 and i am Left joining Table1 on Table2 with Table1.PrimaryKey = Table2.ForeignKey. It does return all the rows from both tables but in some rows, due to no record in Table2 for the join condition, the PrimaryKey field value is missing for Table1. Here is my code
$this->db->select('*');
$this->db->from('CI_Articles_Tbl');
$this->db->join('CI_Article_Images_Tbl',
'CI_Articles_Tbl.roflArticle_ID=CI_Article_Images_Tbl.roflArticle_ID','left');
$this->db->group_by('CI_Articles_Tbl.roflArticle_ID');
$query = $this->db->get();
return $query->result_array();
What is the problem in my query and what is its possible solution. Any help will be highly appreciated.
回答1:
You have select table.*
Try this code.
$this->db->select('CI_Articles_Tbl.*');
回答2:
My Answer for my own question is this but let me first Thank "Lighter"! His Code helped me corrected my query,
Suppose you have Two Tables Table1 and Table2 and you want to LEFT JOIN Table1 on Table2 or in other sense, You want all rows from both tables Whether or not a reference matches or not matches in both tables Table1 and Table2. For example you want like this
Table1.P1 = Table2.P1
What i was doing that i went ahead and selected all fields from Table1 and then straight away gave the join condition on Table2 which is Wrong because sometimes Table1.P1 will NOT have a match Table2.P1, in such a case, rows will come but the value Table1.P1 will be missing.
What you have to do is to show specifically what fields you want from what tables EXCEPT THE field of Table2 that you are using in Join condition. Like this Table1.* Table2.* except Table2.P1 (NOTE: VERY IMPORTANT)
My Code is here for any reference purposes
$this->db->select('CI_Articles_Tbl.*,CI_Article_Images_Tbl.roflArticleImage_ID,CI_Article_Images_Tbl.roflArticleImage_Ext,CI_Users_Tbl.*');
$this->db->from('CI_Articles_Tbl','CI_Article_Images_Tbl','CI_Users_Tbl');
$this->db->join('CI_Article_Images_Tbl','CI_Articles_Tbl.roflArticle_ID=CI_Article_Images_Tbl.roflArticle_ID','left outer');
$this->db->join('CI_Users_Tbl','CI_Articles_Tbl.roflUser_ID=CI_Users_Tbl.roflUser_ID');
$this->db->group_by('CI_Articles_Tbl.roflArticle_ID');
$query = $this->db->get();
return $query->result_array();
来源:https://stackoverflow.com/questions/20418791/codeigniter-two-tables-left-join-does-not-return-join-condition-id-of-left-table