1. 程式人生 > >查詢資料庫時 採用 分組查詢並 獲取分組後組中最新的一條資料

查詢資料庫時 採用 分組查詢並 獲取分組後組中最新的一條資料

使用原生可採用:

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