【问题标题】:join 3 tables in mysql codeigniter在 mysql codeigniter 中加入 3 个表
【发布时间】:2012-07-16 12:10:43
【问题描述】:

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

  1. tbl_roles(role_id,role_name);
  2. tbl_users(id,role_id,username,email,password);
  3. tbl_tickets_replies(id,ticket_id,user_id,role_id,cmets)

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

  1. 来自 tbl_users 的用户名。
  2. 来自 tbl_roles 的角色名称。
  3. 来自 tbl_tickets 的 cmets

其中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;
     }

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

显示此错误:-

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

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

选择tbl_tickets_replies.comments, tbl_users.username, tbl_roles.role_name FROM (tbl_tickets_replies, tbl_tickets_replies) 加入 tbl_users 开启 tbl_users.id = tbl_tickets_replies.user_id加入tbl_roles开启 tbl_roles.role_id=tbl_tickets_replies.role_id 在哪里 tbl_tickets_replies.ticket_id = '6'

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

行号:330`

【问题讨论】:

  • 删除 from 子句或从 $this->db->get() 中删除表。你不需要两者。你得到什么错误?
  • 您没有删除 $this->db->from 或删除了:$this->db->get();
  • 感谢 yan 通过删除 $this->db->from() 解决了

标签: php mysql codeigniter join


【解决方案1】:

有条件的加入。

$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();

【讨论】:

    【解决方案2】:

    您指的是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');
    }
    

    【讨论】:

      【解决方案3】:

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

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

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

      $comments = $this->db->get(); //change this
      

      【讨论】:

      • 使用该活动记录功能,查询可以变得简单
      • 如果你应该动态地构建你的查询,那么原始 sql 是困难的(或不可能的)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 2016-11-16
      • 2013-12-01
      • 2020-10-24
      • 2012-01-14
      • 1970-01-01
      相关资源
      最近更新 更多