从第二张表中获取最新记录

时间:2018-02-01 13:02:18

标签: php mysql codeigniter

我拿到第一份工资的所有员工名单,我希望所有有最新薪水的员工都记入。

员工-表

emp_id | emp_name
-------|--------- 
101    | Andrew
102    | John
103    | Alex

薪酬-表

sal_id | emp_id | month                 | salary
-------|--------|-----------------------|-------
201    | 101    | 1st jan 2018          | 10000
202    | 101    | 1st feb 2018          | 20000
203    | 101    | 1st march2018         | 30000
204    | 102    | 1st jan 2018          | 10000
205    | 102    | 1st feb 2018          | 20000
206    | 102    | 1st march2018         | 30000
207    | 103    | 1st jan 2018          | 10000
208    | 103    | 1st feb 2018          | 20000
209    | 103    | 1st march2018         | 30000

我想仅提取最新月薪的所有员工名单。 (所有有3月工资的员工)

提前致谢。

2 个答案:

答案 0 :(得分:0)

此代码应该有效:

<?php

    $date = date('F Y');

    $sql = "SELECT * FROM Employee-table et 
            INNER JOIN Salary-Table st ON et.emp_id = st.emp_id 
            WHERE st.month LIKE '%$date%'";

答案 1 :(得分:0)

$date = date('F Y');

$saleries = $this->db->select('e.*, s.salary')
->join('Salary-Table s','s.emp_id = e.emp_id')
->like($date, 'match')
//order by the month and the group by emp id to give you the latest
->order_by('s.month', 'asc')
->group_by('e.emp_id')
//return results as an array of arrays
->get('Employee-table e')->result_array();

https://www.codeigniter.com/userguide3/database/query_builder.html