我有下表,用于自动回复,它跟踪交换给每个人的所有消息。它按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的方式组合这两个查询?
答案 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