我希望每次执行此语句时都不插入数据。它应该只能每天有效地插入一次数据。多数民众赞成我想要这样做。我的逻辑在这里有什么问题吗?我正在使用date(now())
,因此它会插入今天的日期。我需要这是一个幂等插入。
INSERT INTO newsletter_subscription_counts
(query_date, community_id, mailing_list, subscription_count)
SELECT date(now()), a.community_id,
a.newsletter_type::mail_list_types,
count(a.subscriber_user_id)
FROM
newsletter_subscribers_main a
LEFT OUTER JOIN newsletter_subscription_counts b
ON (a.community_id = b.community_id)
AND (a.newsletter_type::mail_list_types = b.mailing_list)
AND (a.created_at = b.query_date)
WHERE b.query_date is null
AND b.mailing_list is null
GROUP BY a.community_id, a.newsletter_type, a.created_at
答案 0 :(得分:3)
INSERT INTO newsletter_subscription_counts
(query_date, community_id, newsletter_t, subscription_count)
SELECT now()::date
,a.community_id
,a.newsletter_type
,count(*)
FROM newsletter_subscribers_main a
LEFT JOIN newsletter_subscription_counts b
ON a.community_id = b.community_id
AND a.newsletter_type::mail_list_types = b.mailing_list
AND a.created_at = b.query_date
WHERE a.created_at::date = now()::date
AND b.query_date is null
GROUP BY a.community_id, a.newsletter_type;
删除了一些噪音,改进了格式,最重要的是添加了WHERE
子句:
WHERE a.created_at::date = now()::date
如果created_at
已经输入date
,则不需要演员。
还要考虑我对你上一个问题的回答,我已经猜到了你的问题:
Need help understanding a complex query with multiple join conditions
只是,我在那里的猜测照顾了尚未插入的所有日子(并且更适合IMO)。