如何获取最后访问的项目-sql

b5lpy0ml  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(195)

我有一张这样的table:
我的表名是: user_viewed_offer ```
id user_id coupon_id
1 1 65
2 1 58
3 1 65
4 1 65
5 1 34
6 1 46
7 1 24

我要检索这些ID:

4-5-6-7

我曾经 `group by` 但它会返回这些ID:

"[{"id":"7"},{"id":"6"},{"id":"5"},{"id":"2"}]"

我的职能:

$this->db->select('id');
$this->db->from('user_viewed_offer');
$this->db->where('user_id',$user_id);
$this->db->group_by('coupon_id');
$this->db->order_by('id','desc');
$this->db->limit('4');
$data['coupons'] = $this->db->get()->result();
var_dump(json_encode($data['coupons']));
exit();

我想我用 `distinct` 但我不知道该怎么用。
tpxzln5u

tpxzln5u1#

将您的表联接到查找最近 id 每个用户、每个优惠券的值。

SELECT t1.id
FROM yourTable t1
INNER JOIN
(
    SELECT user_id, coupon_id, MAX(id) AS max_id
    FROM yourTable
    GROUP BY user_id, coupon_id
) t2
    ON t1.user_id = t2.user_id     AND
       t1.coupon_id = t2.coupon_id AND
       t1.id = t2.max_id
WHERE
    t1.user_id = 1;
lskq00tm

lskq00tm2#

似乎要从优惠券id中的最大值开始检索id

select id from user_viewed_offer
where id => (
  select max(id)
  from user_viewed_offer 
  where coupon_id  =  (
    select max(coupon_id)
    from user_viewed_offer 
  ) 
)

相关问题