Php 如何获取上次访问的项目-sql
我有一张这样的桌子: 我的表名是:Php 如何获取上次访问的项目-sql,php,mysql,sql,codeigniter,Php,Mysql,Sql,Codeigniter,我有一张这样的桌子: 我的表名是:user\u viewed\u offer id user_id coupon_id 1 1 65 2 1 58 3 1 65 4 1 65 5 1 34 6 1 4
user\u viewed\u 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
"[{"id":"7"},{"id":"6"},{"id":"5"},{"id":"2"}]"
我使用了groupby
,但它返回以下ID:
4-5-6-7
"[{"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
语句,但我不知道该如何使用它。将您的表连接到一个子查询,该子查询为每个用户、每个优惠券查找最新的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;
似乎要从优惠券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
)
)
如果您想要用户1的最后4个id,然后删除
->group\u by('优惠券id')
子句,或者编辑您的问题并添加详细信息,说明为什么需要这4个id?@MKhalidJunaid我看到了,58
缺失:-(