V
V
Vyacheslav2015-01-26 12:10:42
SQL
Vyacheslav, 2015-01-26 12:10:42

How to pull last row in query with group by?

Hello sql-guru
has already broken his brain and fingers on the keyboard, but I can’t get the last entry from the array
, there is such a funka:

function get_all_threads_list($user_id, $order_by = 'DESC')
    {
        $sql = 'SELECT m.*, s.status, t.subject, ' . USER_TABLE_USERNAME .
        ' FROM ' . $this->db->dbprefix . 'msg_participants p ' .
        ' JOIN ' . $this->db->dbprefix . 'msg_threads t ON (t.id = p.thread_id) ' .
        ' JOIN ' . $this->db->dbprefix . 'msg_messages m ON (m.thread_id = t.id) ' .
        ' JOIN ' . $this->db->dbprefix . USER_TABLE_TABLENAME . ' ON (' . USER_TABLE_ID . ' = m.sender_id) '.
        ' JOIN ' . $this->db->dbprefix . 'msg_status s ON (s.message_id = m.id AND s.user_id = ? ) ' .
        ' WHERE p.user_id = ? group by m.thread_id ORDER BY t.id ' . $order_by. ', m.cdate '. $order_by;

        $query = $this->db->query($sql, array($user_id, $user_id));
        return $query->result_array();
}

in a nutshell - it forms an array of messages in conjunction with the table of recipients, naturally, because of group by, it displays only the first value, if group by is removed, then just the entire list of messages is displayed. The solution is somewhere on the surface, but I can not finish it. Will you kindly help?
----------
UPD:
sqlfiddle.com/#!2/b1dab2/1
now displays id 2 and 1
if GROUP BY m.thread_id is removed, id 4, 2, 1 will be displayed,
but it is necessary that id be displayed 4 and 1
i.e. in fact, the last value should be selected in group_by, now the first one is selected

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Shein, 2015-01-26
@nskarl

Try like this:
And the cdateindex would not hurt.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question