复杂的sql查询结合'select max'和select count(*)查询

时间:2016-12-09 15:56:38

标签: sql postgresql

我有下表,用于自动回复,它跟踪交换给每个人的所有消息。它按match_id

跟踪每个人
CREATE TABLE public.sms_log
(
  id bigint NOT NULL DEFAULT nextval('sms_log_id_seq'::regclass),
  source text NOT NULL,
  destination text NOT NULL,
  message text,
  insert_time timestamp with time zone DEFAULT now(),
  reply_batch boolean DEFAULT false,
  own_reply boolean DEFAULT false,
  match_id text NOT NULL,
  CONSTRAINT sms_log_pkey PRIMARY KEY (id),
  CONSTRAINT sms_log_match_id_fkey FOREIGN KEY (match_id)
      REFERENCES public.match (match_id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE CASCADE
)

现在我有以下查询,如果发送的最后一条消息match_id为false,则会返回own_reply行。 (几乎检查是否有人从系统上次回复时向系统发送了一条消息)

QUERY A

select m.* 
from sms_log m 
where m.source <> 'MYNUMBER' 
  and m.destination = 'MYNUMBER' 
  and m.insert_time = (select max(insert_time) 
                       from sms_log 
                       where match_id = m.match_id 
                       group by match_id)

然后我在程序中使用循环来确定程序通过使用以下查询回复match_id的次数

QUERY B

select count(*) from sms_log where match_id = ? and reply_batch = true

是否可以将QUERY A仅在reply_batch计数小于3时返回match_ids的方式组合这两个查询?

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

select m.* 
from sms_log m 
where m.source <> 'MYNUMBER' 
  and m.destination = 'MYNUMBER' 
  and m.insert_time = 
       (select max(insert_time) 
        from sms_log 
        where match_id = m.match_id group by match_id)
  and (select count(*) 
       from sms_log as sl 
       where sl.match_id = m.match_id 
         and sl.reply_batch = true) < 3