-1

我希望每次执行此语句时都不会插入数据。它应该每天只有效地插入一次数据。这就是我想要做的。我这里的逻辑有问题吗?我正在使用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
4

1 回答 1

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已经是 type date,则不需要演员表。

还要考虑我对您上一个问题的回答,我已经猜到了您的问题:
需要帮助理解具有多个连接条件的复杂查询

只是,我在那里的猜测会处理所有尚未插入的日子(并且最好是 IMO)。

于 2013-06-17T16:51:28.883 回答