查询数据库时 采用 分组查询并 获取分组后组中最新的一条数据

使用原生可采用:

SELECT
    * 
FROM
    lease_note ln 
WHERE
    ln.delete_time IS NULL 
    AND ln.id = ( SELECT lns.id FROM lease_note lns WHERE lns.contract_id = ln.contract_id ORDER BY create_time DESC LIMIT 1 )

使用thinkphp5.1 查询构造器查询,可分为两部查询

 $baseQuery = NoteModel::where('id', '<>', -1)
            ->where('is_rent', $input['is_rent'])
            ->order('create_time', 'desc');
        if (isset($input['staff_id']) && !empty($input['staff_id'])) {
            $baseQuery->where('staff_id', 'in', $input['staff_id']);
        }
        if (isset($input['sender_id']) && !empty($input['sender_id'])) {
            $baseQuery->where('sender_id', 'in', $input['sender_id']);
        }
        if (isset($input['department_id']) && !empty($input['department_id'])) {
            $baseQuery->where('department_id', 'in', $input['department_id']);
        }
        if (isset($input['date_range']) && !empty($input['date_range'])) {
            $baseQuery->whereBetweenTime('create_time', $input['date_range'][0] . ' 00:00:00', $input['date_range'][1] . ' 23:59:59');
        }
        if (isset($input['contract_id']) && !empty($input['contract_id'])) {
            $baseQuery->where('contract_id', 'in', $input['contract_id']);
        }
        if (isset($input['search']) && !empty($input['search'])) {
            $baseQuery->where('address', '%' . $input['search'] . '%');
        }
        $to_be_count = clone $baseQuery;
        if (isset($input['output']) && $input['output'] == 1) {
         //查询出分组后的最大id
            $one = $baseQuery->field('max(id)')->group('contract_id')->select();  
            $ones = $one->toArray();
            foreach($ones as $val){
                foreach($val as $v){
                    $two[] = $v;
                }
            }
            $twos = implode(",",$two);
            $daochu = $to_be_count->where('id','IN',$twos)->select();     //获取到 需要导出的数据
        }

打印出的 第一条sql 为

SELECT
    max( id ) 
FROM
    `lease_note` 
WHERE
    ( `id` <> - 1 AND `is_rent` = 1 ) 
    AND `lease_note`.`delete_time` IS NULL 
GROUP BY
    `contract_id` 
ORDER BY
    `create_time` DESC

第二条sql 为:

SELECT
    * 
FROM
    `lease_note` 
WHERE
    ( `id` <> - 1 AND `is_rent` = 0 AND `id` IN ( 71, 39, 43 ) ) 
    AND `lease_note`.`delete_time` IS NULL 
ORDER BY
    `create_time` DESC

猜你喜欢

转载自blog.csdn.net/Json159/article/details/81133082