[英]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.