CodeIgniter-按顺序分组(未按预期工作) [英] CodeIgniter - Group by with order by not working as expected

查看:74
本文介绍了CodeIgniter-按顺序分组(未按预期工作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我得到了这个查询:

So I got this query:

    $CI->db->where('user_id', $CI->session->userdata('user_id'));
    $CI->db->where('amount >', 0);
    $CI->db->order_by('ur_time', 'desc');
    $CI->db->group_by('resource_id');
    $query = $CI->db->get('users_resources');
    $resources = $query->result();

我的问题是:order_by'ur_time'并没有真正起作用.如果我有2行,其中一行的金额为10000和ur_time 1384303464,另一行的金额为100和ur_time 1384304656我仍然会得到该行,金额为10000.

My problem is: The order_by 'ur_time' doesn't really work. If I got 2 rows, one with amount 10000 and ur_time 1384303464 and another row with amount 100 and ur_time 1384304656 I still get the row with amount 10000 as result.

我在做什么错了?

也许我必须解释一下.假设我有一些行:

Maybe I have to explain it a bit. Let's say I got some rows:

ur_id | ur_time     | user_id | resource_id | amount

1     | 1384304656  | 1       | 1           | 100
2     | 1384303464  | 1       | 1           | 10000
3     | 1384303464  | 1       | 2           | 200
4     | 1384304656  | 1       | 2           | 20000

我想在这里得到的结果是:两行,一个具有ur_id 1,另一个具有ur_id 4,因为对于每个resource_id,我都希望具有ur_time最高的行.我希望现在很清楚.

What I'd like to get here as result: Two rows, the one with ur_id 1 and the one with ur_id 4 because for each resource_id I want the row with the highest ur_time. I hope it's clear now.

PS:我需要金额> 0子句,因为可能会有负数,但我不希望它们出现在结果中.

PS: I need the amount > 0 clause because there can be negative amounts but I don't want them in the result.

推荐答案

尝试将其添加到查询中,看看它们是否会合并到您的select语句中

Try adding this in your query see if they will combine in your select statement

$CI->db->select('*');
$CI->db->select_max('ur_time' , 'max_ur_time'); // this will produce max(ur_time) as max_ur_time
$CI->db->where('user_id', $CI->session->userdata('user_id'));
$CI->db->where('amount >', 0);
$CI->db->order_by('ur_time', 'desc');
$CI->db->group_by('resource_id');
$query = $CI->db->get('users_resources');
$resources = $query->result();

这篇关于CodeIgniter-按顺序分组(未按预期工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆