【问题标题】:How to get last visited items - sql如何获取上次访问的项目 - sql
【发布时间】:2018-01-01 09:02:30
【问题描述】:

我有一张这样的桌子:

我的表名是: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 语句,但我不知道应该如何使用它。

【问题讨论】:

  • 如果您想要用户 1 的最后 4 个 id 然后删除 ->group_by('coupon_id') 子句,您的查询看起来不错,或者编辑您的问题并添加详细信息为什么您想要这 4 个 id?

标签: php mysql sql codeigniter


【解决方案1】:

将您的表加入到子查询中,该子查询为每个用户、每个优惠券查找最新的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;

【讨论】:

  • @MKhalidJunaid 我明白了,58 不见了:-(
【解决方案2】:

您似乎想从 coupon_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 
  ) 
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    相关资源
    最近更新 更多