将功能添加到已经很复杂的查询中

时间:2016-03-14 23:30:01

标签: sql postgresql

我有下表记录聊天消息

CREATE TABLE public.message_log
(
  id integer NOT NULL DEFAULT nextval('message_log_id_seq'::regclass),
  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,
  insert_time timestamp with time zone DEFAULT now(),
  CONSTRAINT message_log_pkey PRIMARY KEY (id),
  CONSTRAINT message_log_message_from_id_to_id_match_id_unix_timestamp_key UNIQUE (message, from_id, to_id, match_id, unix_timestamp)
)

聊天对话具有相同的match_id

我有以下查询返回match_ids列表,其中与match_id相关的最后一条消息(聊天对话的最后一条消息)来自非帐户持有者(own_account = false)查询工作正常

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 
)

我想修改上面的查询,它会计算已经回复两次或更多次的聊天对话(我想我们需要使用reply_batch列)。我无法理解它。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

SELECT match_id, replies_count FROM (SELECT match_id, COUNT(*) AS replies_count FROM message_log
WHERE from_id <> ? and to_id = ? GROUP BY match_id) AS replies_counter WHERE replies_count > 1