2015-08-23 43 views
0

我有以下表,記錄聊天消息SQL查詢得到不一致的結果

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

我想出了以下查詢,但它給出了不一致的結果,我d不明白。

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

+1

什麼不一致意味着什麼? –

+0

它的工作原理與某些聊天對話一樣,並返回最後一條消息來自帳戶持有者的chat_ids。所以它不能正常工作。我的查詢是否正確? – Arya

回答

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) 
+0

我認爲它現在正在工作 – Arya

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;