【问题标题】:Where condition based on two database fieldsWhere 条件基于两个数据库字段
【发布时间】:2019-12-30 02:53:45
【问题描述】:

我确实有两张表,分别是雇员和贷款 当我为特定用户输入贷款时,我正在选择用户 employee_id 和贷款金额。 //贷款表格 https://imgur.com/VH6hflw

这些详细信息存储在贷款表中。以及我已经在员工表中存储了一些员工详细信息,例如帐号、员工官方 ID、用户图片。

当我提交贷款表格时,我得到了员工唯一 ID。我会将员工唯一 ID 存储到名为 loan_employee_id 的贷款字段中。

我的问题是,当我从贷款表中检索数据时,我会获得贷款金额,但需要从员工表中获取更多字段。所以我加入了两张表,分别是员工和贷款。

我的数据库结构https://imgur.com/XYxGjVH

public function fetchLoan()
{

    $this->db->select('*');
    $this->db->from('employee');
    $this->db->join('loan','employee.emp_id = loan.employee_loan_id'); 

    $this->db->where(array('loan.employee_loan_id' => "employee.emp_id")  );
    $query= $this->db->get();
    return $query->result_array();
}

这里 where 的条件应该匹配贷款表中的employee_loan_id 和员工表中的emp_id

我如何加入具有上述条件的表,其中条件都从数据库中获取。

【问题讨论】:

  • 您应该通过 dbfiddle 而不是 img 传递您的架构和查询尝试。
  • 您在哪个框架中编写这些查询,CodeIgniter?

标签: php mysql codeigniter join


【解决方案1】:

首先,对应的 MySQL 查询是:

SELECT *                        -- Put field names which are required
FROM loan
INNER JOIN employee ON employee.emp_id = loan.employee_loan_id
WHERE loan.employee_loan_id = 12;     -- Consider we're fetching records for emp_id = 12

对应的代码是:

-- Pass a parameter for employee id for which you want to get loan details.
public function fetchLoan($empId)
{
    $this->db->select('*');
    $this->db->from('employee');
    $this->db->join('loan', 'employee.emp_id = loan.employee_loan_id');
    $this->db->where('employee.emp_id', $empId);
    $query = $this->db->get();
    return $query->result_array();
}

【讨论】:

    【解决方案2】:

    请在此基础数据获取上传递employe_unique_id

    public function fetchLoan($employe_unique_id)
    {
    
        $this->db->select('*');
        $this->db->from('employee');
        $this->db->join('loan','employee.id = loan.employee_id'); 
    
        $this->db->where('employee.id',$employe_unique_id);
        $query= $this->db->get();
        return $query->result_array();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-26
      • 1970-01-01
      • 2012-11-19
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 2021-11-05
      相关资源
      最近更新 更多