[英]join 3 tables in mysql codeigniter
我的數據庫中有3個表: -
role_id, id, id
是相應表的主鍵。 我需要 :-
其中ticket_id
從tbl_tickets_replies
= $ticket_id
來作為參數。
我的模型功能是: -
function fetch_comments($ticket_id){
$this->db->select('tbl_tickets_replies.comments,tbl_users.username,tbl_roles.role_name');
$this->db->where('tbl_tickets_replies.ticket_id',$ticket_id);
$this->db->from('tbl_tickets_replies');
$this->db->join('tbl_users','tbl_users.id = tbl_tickets_replies.user_id');
$this->db->join('tbl_roles','tbl_roles.role_id=tbl_tickets_replies.role_id');
$comments = $this->db->get('tbl_tickets_replies');
return $comments;
}
這顯示數據庫錯誤,即我正在做錯查詢。 我想問一下如何連接三個表來從3個不同的表中獲取數據
此錯誤顯示: -
發生數據庫錯誤
錯誤號碼:1066不唯一的表/別名:'tbl_tickets_replies'
SELECT
tbl_tickets_replies
。comments
,tbl_users
。username
,tbl_roles
。role_name
FROM(tbl_tickets_replies
,tbl_tickets_replies
)tbl_tickets_replies
tbl_users
ONtbl_users
。id
=tbl_tickets_replies
。user_id
tbl_roles
ONtbl_roles
。role_id
=tbl_tickets_replies
。role_id
WHEREtbl_tickets_replies
。ticket_id
='6'文件名:C:\\ wamp \\ www \\ local.helpdesk.com \\ bonfire \\ codeigniter \\ database \\ DB_driver.php
行號:330`
你指的是兩次tbl_tickets_replies
。 試試這個:
function fetch_comments($ticket_id){
$this->db->select('tbl_tickets_replies.comments,
tbl_users.username,tbl_roles.role_name');
$this->db->where('tbl_tickets_replies.ticket_id',$ticket_id);
$this->db->join('tbl_users','tbl_users.id = tbl_tickets_replies.user_id');
$this->db->join('tbl_roles','tbl_roles.role_id=tbl_tickets_replies.role_id');
return $this->db->get('tbl_tickets_replies');
}
對於復雜查詢,我更喜歡使用純SQL,如下所示。
$sql = "SELECT....";
$q = $this->db->query($sql);
順便說一句,嘗試從db-> get函數中刪除表名
$comments = $this->db->get(); //change this
加入條件。
$this->db->select('*'); $this->db->from('articles');
$this->db->join('category', 'category.id = articles.id');
$this->db->where(array('category.id' => 10)); $query =
$this->db->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.