1

我有一个表“消息”,其中包含 id、from、to、datetime、subject、body 列。我想获取每个发件人(来自)的最新消息的主题和正文。

这是我的查询

SELECT min(subject) as tsubject,min(body) as tbody 
FROM messages 
WHERE "to"=28
GROUP BY "from"
ORDER BY "datetime"

这将导致

ERROR:  column "messages.datetime" must appear in the GROUP BY clause or be used in an aggregate function

所以我得到了错误的全部内容,但我不想按“日期时间”对结果进行分组,只是要排序的组,所以 min 从每个组中选择最新消息。

4

2 回答 2

2
SELECT a.*,u.name,m.subject,m.body FROM
(SELECT "from",max("datetime") as sent
FROM messages 
WHERE "to" = 31
GROUP BY "from") a
LEFT JOIN users u ON a."from" = u.id
LEFT JOIN messages m ON a.sent=m."datetime" AND a."from"=m."from"
于 2012-09-29T08:35:43.850 回答
1
select subject, body, m."from"
from (
    SELECT 
        id,
        "from",
        max("datetime")
    FROM messages 
    WHERE "to" = 28
    group by id, "from"
    ) s 
    inner join 
    messages m on m.id = s.id
ORDER BY "datetime" desc
于 2012-09-27T14:02:31.443 回答