简体   繁体   English

CodeIgniter-按顺序分组(未按预期工作)

[英]CodeIgniter - Group by with order by not working as expected

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();

My problem is: The order_by 'ur_time' doesn't really work. 我的问题是:order_by'ur_time'并没有真正起作用。 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. 如果我有2行,其中一行的金额为10000和ur_time 1384303464,另一行的金额为100和ur_time 1384304656我仍然会得到该行,金额为10000。

What am I doing wrong? 我究竟做错了什么?

EDIT: 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

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. 我想在这里得到的结果是:两行,一个具有ur_id 1,另一个具有ur_id 4,因为对于每个resource_id,我都希望具有ur_time最高的行。 I hope it's clear now. 我希望现在很清楚。

PS: I need the amount > 0 clause because there can be negative amounts but I don't want them in the result. PS:我需要数量> 0子句,因为可能会有负数,但我不希望它们出现在结果中。

Try adding this in your query see if they will combine in your select statement 尝试在查询中添加此内容,看看它们是否会合并到您的select语句中

$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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM