如何从sqlitedatabase中的表中获取每个组的第一行?

时间:2016-05-25 08:20:04

标签: mysql sqlite

我的sqlite数据库中有一个表消息。这个表有三列msg_id,sender_id,msg_body。我需要为每个user_id获取一条最新消息,这些消息应按desc顺序排序。 例如。我的消息表是

 msg_id | sender_id | msg_body
--------+-----------+----------
   1    |    18     |"something"
   2    |    18     |"something"
   3    |    19     |"something"
   4    |    19     |"something"

我想要的是桌子: -

msg_id | sender_id | msg_body
-------+-----------+----------
  4    |    19     |"something"
  2    |    18     |"something"

3 个答案:

答案 0 :(得分:0)

一种选择是使用包含每个INNER JOIN组的最新记录的子查询来执行原始表的sender_id

SELECT t1.msg_id, t1.sender_id, t1.msg_body
FROM yourTable t1
INNER JOIN
(
    SELECT sender_id, MAX(msg_id) AS max_msg_id
    FROM yourTable
    GROUP BY sender_id
) t2
    ON t1.msg_id = t2.max_msg_id AND t1.sender_id = t2.sender_id

请按照以下链接查看正在运行的演示:

SQLFiddle

答案 1 :(得分:0)

试试这个:

SELECT t1.*
FROM mytable AS t1
JOIN (
   SELECT sender_id, MAX(msg_id) AS max_msg_id
   FROM mytable
   GROUP BY sender_id
) AS t2 ON t1.sender_id = t2.sender_id AND t1.msg_id = t2.max_msg_id

答案 2 :(得分:0)

发件人的最后一条消息显示。

SELECT * FROM messagees group by sender_id order by id msg_id