【问题标题】:MySQL join shows multiple recordsMySQL join 显示多条记录
【发布时间】:2014-05-29 14:42:40
【问题描述】:

我正在使用 CodeIgniter,并且在我的 sql 连接查询中它得到了重复的值。例如,如果tbl_employee_contact 有两个联系号码,它会显示相同的记录两次,每个记录的联系号码不同。如何只显示一条记录?

这是我的模特

function get_records(){
    $this->db->select(array(
         'tbl_employee_registration.emp_id',
         'tbl_employee_registration.emp_fname',
         'tbl_employee_registration.emp_email',
         'tbl_employee_registration.emp_status',
         'tbl_employee_contact.emp_contact',    
    ));
    $this->db->from('tbl_employee_registration');
    $this->db->join('tbl_employee_contact','tbl_employee_contact.emp_id=tbl_employee_registration.emp_id');

    $query = $this->db->get();
    return $query->result();
}

这是我的控制器

function manage_operators(){
    $data = array();
    if($query = $this->mod_employee->get_records())
    {
        $data['records'] = $query;
    }
    $this->load->view('admin/admin_manage_operators',$data);
}

【问题讨论】:

  • 这不是代码点火器问题,从技术上讲,它根本不是问题。这就是 SQL 连接的工作方式。如果您正在对一对多关系执行联接,那么您将获得一张表的“重复”,以及联接表的所有不同可能性。
  • 您能否举例说明导致问题的 tbl_employee_registration 和 tbl_employee_contact?
  • Yes 看起来像它的一对多关系,因此它显示多行。那么您希望如何显示数据,您将保留哪一行以及从选择中删除哪一行?
  • @Abhik Chakraborty 没关系。任意行
  • @Scott 我在帖子中添加了数据库图像

标签: php mysql sql codeigniter


【解决方案1】:

您可以使用group_by

 $this->db->group_by("your table");

你的模型最终会是这个样子

 function get_records(){
        $this->db->select(array(
            'tbl_employee_registration.emp_id',
            'tbl_employee_registration.emp_fname',
            'tbl_employee_registration.emp_email',
            'tbl_employee_registration.emp_status',
            'tbl_employee_contact.emp_contact',    
        ));
        $this->db->from('tbl_employee_registration');
        $this->db->join('tbl_employee_contact','tbl_employee_contact.emp_id=tbl_employee_registration.emp_id');
        $this->db->group_by("tbl_employee_registration.emp_id");

        $query = $this->db->get();
        return $query->result();
    }

【讨论】:

    【解决方案2】:

    您需要所谓的GROUP BY 或将DISTINCT 添加到您的选择查询中。

    $this->db->select(array(
        'DISTINCT  tbl_employee_registration.emp_id',
        'DISTINCT  tbl_employee_registration.emp_fname',
        'DISTINCT  tbl_employee_registration.emp_email',
        'DISTINCT  tbl_employee_registration.emp_status',
        'DISTINCT  tbl_employee_contact.emp_contact',    
    ));
    

    或者您可以选择所有数据,但在循环中只需添加到具有唯一 ID 的数组,例如

    $arr[$ID][] = $record

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多