group_by和order_by与codeigniter

时间:2012-03-18 16:07:19

标签: php mysql codeigniter

我想弄明白这一点,没有运气。我一直得到一些奇怪的结果!首先,我有一个包含一些行的MySQL数据库,结构如下所示,

ID MESSAGE_ID 信息 时间 DATE

现在,message_id可以多次相同,这就是我的问题开始的地方。我想按ID选择dubplicated message_ID排序的最后一行。

所以,假设我有一个正常的get请求,结果看起来像这样,

Array
(
    [0] => Array
        (
            [id] => 3
            [message_id] => 1
            [from_user_id] => 3
            [to_user_id] => 1
            [message] => last
            [time_sent] => 1331874924
            [date_sent] => 16/03/2012
            [opened] => 0
            [ip] => ::1
            [deleted] => 0
            [reported] => 0
        )

    [1] => Array
        (
            [id] => 2
            [message_id] => 1
            [from_user_id] => 3
            [to_user_id] => 1
            [message] => middle
            [time_sent] => 1331874920
            [date_sent] => 16/03/2012
            [opened] => 0
            [ip] => ::1
            [deleted] => 0
            [reported] => 0
        )

    [2] => Array
        (
            [id] => 1
            [message_id] => 1
            [from_user_id] => 3
            [to_user_id] => 1
            [message] => first
            [time_sent] => 1331874916
            [date_sent] => 16/03/2012
            [opened] => 0
            [ip] => ::1
            [deleted] => 0
            [reported] => 0
        )

    [3] => Array
        (
            [id] => 4
            [message_id] => 2
            [from_user_id] => 3
            [to_user_id] => 1
            [message] => test
            [time_sent] => 1331874916
            [date_sent] => 16/03/2012
            [opened] => 0
            [ip] => ::1
            [deleted] => 0
            [reported] => 0
        )

) 

现在,我想要的是删除dubplicated message_id并且只获取它(注意它应该如何按ID排序)

Array
(
    [0] => Array
        (
            [id] => 3
            [message_id] => 1
            [from_user_id] => 3
            [to_user_id] => 1
            [message] => last
            [time_sent] => 1331874924
            [date_sent] => 16/03/2012
            [opened] => 0
            [ip] => ::1
            [deleted] => 0
            [reported] => 0
        )

    [1] => Array
        (
            [id] => 4
            [message_id] => 2
            [from_user_id] => 3
            [to_user_id] => 1
            [message] => test
            [time_sent] => 1331874916
            [date_sent] => 16/03/2012
            [opened] => 0
            [ip] => ::1
            [deleted] => 0
            [reported] => 0
        )

)

我之前一直在尝试的是,

$this->db->order_by(‘id’, ‘DESC’);
$this->db->group_by(‘message_id’);

$this->db->group_by(‘message_id’);
$this->db->order_by(‘id’, ‘DESC’);

但是我没有得到message_id的最新结果,只有第一个(看起来它在删除之前没有找到或者什么?)

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

我在桌子上取得了成功:

select * from 
    (select * from da_user_messages order by id desc) t 
where receiver=1 group by msg_session

在你的情况下,msg_session是message_id,receiver是to_user_id,da_user_messages是你的表名。