在mysql codeigniter中加入3个表

avi*_*hse 3 php mysql join codeigniter

我的数据库中有3个表: -

  1. tbl_roles(ROLE_ID,ROLE_NAME);
  2. tbl_users(ID,ROLE_ID,用户名,电子邮件,密码);
  3. tbl_tickets_replies(ID,TICKET_ID,USER_ID,ROLE_ID,评论)

role_id, id, id是相应表的主键.我需要 :-

  1. 来自tbl_users的用户名.
  2. 来自tbl_roles的role_name.
  3. 来自tbl_tickets的评论

其中ticket_idfrom 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;
     }
Run Code Online (Sandbox Code Playgroud)

这显示数据库错误,即我正在做错查询.我想问一下如何连接三个表来从3个不同的表中获取数据

此错误显示: -

发生数据库错误
错误号:1066

不唯一的表/别名:'tbl_tickets_replies'

选择tbl_tickets_replies.comments,tbl_users.username, tbl_roles.role_nameFROM( tbl_tickets_replies, tbl_tickets_replies)JOIN tbl_usersON tbl_users.id= tbl_tickets_replies.user_idJOIN tbl_rolesON tbl_roles.role_id= tbl_tickets_replies.role_idWHERE tbl_tickets_replies.ticket_id='6'

文件名:C:\ wamp\www\local.helpdesk.com\bonfire\codeigniter\database\DB_driver.php

行号:330`

Yan*_*erk 6

你指的是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');
}
Run Code Online (Sandbox Code Playgroud)