簡體   English   中英

在mysql codeigniter中加入3個表

[英]join 3 tables in mysql 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_idtbl_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 commentstbl_users usernametbl_roles role_name FROM( tbl_tickets_repliestbl_tickets_repliestbl_tickets_replies tbl_users ON tbl_users id = tbl_tickets_replies user_id tbl_roles ON tbl_roles role_id = tbl_tickets_replies role_id WHERE tbl_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM