問題描述
所以我得到了這個查詢:
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.
推薦答案
嘗試將其添加到您的查詢中,看看它們是否會合并到您的選擇語句中
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 - 按順序分組,但未按預期工作的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!