2013-08-05 21 views
1

基本上,我已經有了這種編碼約定,即任何主鍵都是ID,我將調用列名「id」。所以我的問題出現了。我加入了兩張表,我得到了第二張表的ID而不是第一張表。我知道如果我使用選擇「artists.id,...」它會工作,但我想知道是否有修復與使用「選擇*」,這將是更好的未來擴展(新的colums會來...) 。CodeIgniter PHP - 如何選擇使用「select *」在聯接中選擇哪個ID

這裏是我的模型:

$this->db->select('*'); 
$this->db->from('artists'); 
$this->db->join('categories', 'artists.category_id = categories.id'); 
$this->db->where('id', $id); 
$this->db->limit(1); 

隨着print_r的,我可以看到我得到的所有列(但只有1號,這是從類別表,而不是藝術家表)沒有任何表前綴。

+1

編號避免「SELECT *」。 – Strawberry

回答

3

你應該用表的別名

$this->db->select('a.id as artist_id, c.id as category_id, a.column2,c.column3'); 
$this->db->from('artists a'); 
$this->db->join('categories c', 'a.category_id = c.categories.id'); 
$this->db->where('a.id', $id); 
$this->db->limit(1); 

符合你的列如果您希望繼續使用SELECT *

$this->db->select('a.*, c.*, a.id as artist_id, c.id as category_id'); 
$this->db->from('artists a'); 
$this->db->join('categories c', 'a.category_id = c.categories.id'); 
$this->db->where('a.id', $id); 
$this->db->limit(1); 

請記住,上一次重複的列將被退回。因此,a.*,c.*將返回c.id作爲idc.*,a.*將返回a.id作爲id

+0

打敗我吧。好的答案 – envysea

+0

你可以隨時編輯我的答案並添加一些鏈接供參考;) – user20232359723568423357842364

+0

嗯,我知道:D。我想知道是否有一種方法可以使用「select *」:P。所以我想沒有? –

0

我認爲爲了節省您的麻煩和未來,請始終使用列名稱前面的表格。 這裏沒有任何邏輯,當你查找*時,它表示所有的字段,例如在Oracle中,你將得到前面表的所有字段,我猜它在MySQL中沒有,但如果我是你,我不會冒險吧。