如何在mysql中按具有最新创建日期的产品ID分组?

时间:2018-11-05 03:52:27

标签: mysql select

我有如下选择语句和示例输出:-

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 

enter image description here

如何按创建日期最近的产品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;
    }

2 个答案:

答案 0 :(得分:3)

  • 首先,这里不需要Left Join,因为您也在user_product_history表上进行过滤。似乎您只想显示具有creation_date对应的user_id = 124的那些产品。因此,您只需使用Inner Join即可。
  • 在派生表(子选择查询)中,为每个creation_date确定product_id的最大值。
  • 现在,使用此结果集连接到product_idcreation_date上的主表,以获取完整的行。

尝试以下操作:

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 = 124 
join (select product_id, 
             MAX(creation_date) AS max_creation_date
      from user_product_history 
      where user_id = 124 
      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

答案 1 :(得分:0)

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 and
    uph.creation_date = (select
                             max(creation_date)
                         from 
                             user_product_history) 
order by 
    uph.creation_date desc