我有如下选择语句和示例输出:-
select uph.creation_date, p.name,p.product_id from product p
left join user_product_history uph on p.product_id = uph.product_id
where uph.user_id = 124 order by uph.creation_date desc
如何按具有最新创建日期的产品 ID 分组?请帮忙。谢谢你。
使用 PHP API .model 文件编辑
// ~/user/product_history
public function product_history($data) {
$sql = 'select uph.creation_date,
p.name,
p.product_id
from product p
join user_product_history uph
on p.product_id = uph.product_id and
uph.user_id = ?
join (select product_id,
MAX(creation_date) AS max_creation_date
from user_product_history
where user_id = ?
group by product_id) dt
on dt.product_id = uph.product_id and
dt.max_creation_date = uph.creation_date
order by uph.creation_date desc';
$result = $this->db->query($sql, array($data['user_id']));
$records = array();
foreach( $result->result_array() as $r ) {
$r['product_id'] = (int) $r['product_id'];
$r['sub_category_id'] = (int) $r['sub_category_id'];
$r['merchant_id'] = (int) $r['merchant_id'];
if (!isset($r['price_discount'])) $r['price_discount'] = '';
$records[] = $r;
}
return $records;
}
