3

我的数据库中有 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,comments)

role_id, id, id是对应表的主键。我需要 :-

  1. 来自 tbl_users 的用户名。
  2. 来自 tbl_roles 的角色名称。
  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;
     }

这显示数据库错误,即我做错了查询。我想问如何加入三个表以从 3 个不同的表中获取数据

显示此错误:-

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

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

选择tbl_tickets_repliescomments, tbl_users. username, tbl_roles. role_name从 ( tbl_tickets_replies, )tbl_tickets_replies加入tbl_users。= 。加入。_ = 。在哪里 。='6'tbl_usersidtbl_tickets_repliesuser_idtbl_rolestbl_rolesrole_idtbl_tickets_repliesrole_idtbl_tickets_repliesticket_id

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

行号:330`

4

3 回答 3

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');
}
于 2012-07-17T14:47:32.840 回答
0

对于复杂的查询,我更喜欢使用如下的普通 SQL。

$sql = "SELECT....";
$q = $this->db->query($sql);

顺便说一句,尝试从 db->get 函数中删除表名

$comments = $this->db->get(); //change this
于 2012-07-17T14:41:37.380 回答
0

有条件加入。

$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();
于 2017-05-22T10:11:32.177 回答