我有下表记录聊天消息
CREATE TABLE message_log
(
id serial NOT NULL,
message text,
from_id character varying(500),
to_id character varying(500),
match_id character varying(500),
unix_timestamp bigint,
own_account boolean,
reply_batch boolean DEFAULT false,
CONSTRAINT message_log_pkey PRIMARY KEY (id)
)
聊天对话将具有相同的match_id
我想要一个返回match_ids列表的查询,其中与match_id
相关的最后一条消息(聊天会话的最后一条消息)来自非帐户持有者(own_account = false
)
我想出了以下查询,但它给出的结果不一致,我不明白。
select * from message_log
where from_id <> ?
and to_id = ?
and unix_timestamp in ( select distinct max(unix_timestamp)
from message_log group by match_id )
SQL查询中的问号表示帐户持有者的用户ID
答案 0 :(得分:1)
看起来您需要将message_id
绑定回基本查询,否则您可能会从其他消息中获取unix_timestamp:
select m.*
from message_log m
where m.from_id <> ?
and m.to_id = ?
and m.unix_timestamp = ( select max(unix_timestamp)
from message_log
where match_id = m.match_id
group by match_id )
答案 1 :(得分:0)
我建议使用distinct on
。这是Postgres特有的,但是针对这种情况设计:
select distinct on (match_id) ml.*
from message_log ml
where from_id <> ? and to_id = ?
order by match_id, unix_timestamp desc;