SQL Query提供不一致的结果

时间:2015-08-23 00:38:50

标签: sql postgresql

我有下表记录聊天消息

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

2 个答案:

答案 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;