1

我遇到了这个用于执行幂等插入的 github SQL 代码示例。完全按照我想要的方式工作。我不想使用 EXISTS,因为我觉得它有点混乱。可以用连接编码相同的操作吗?

下面是我在 github 上找到的相同代码:https ://github.com/imtiazahmad007/SQL-Tips-Techniques/blob/master/Idempotent_Postgres_Inserts.sql

INSERT INTO users_articles (date, user_id, hit_count)
SELECT a.date, a.user_id, sum(a.article_id as hits)  
from (
select t.* from users_article_details AS t
WHERE NOT EXISTS (
    SELECT 1
    FROM do_not_email_users_tbl
    WHERE email = t.email
    LIMIT 1
)) a 
WHERE NOT EXISTS
(SELECT 1 from users_articles b
WHERE b.date = a.date)
GROUP BY date, user_id
4

2 回答 2

2

我喜欢对这种事情使用外部连接。尝试:

INSERT INTO USERS_ARTICLES (DATE, USER_ID, HIT_COUNT)
  SELECT a.DATE,
         a.USER_ID,
         SUM(a.ARTICLE_ID) AS HITS
    FROM USERS_ARTICLE_DETAILS a
    LEFT OUTER JOIN DO_NOT_EMAIL_USERS_TBL n
      ON (n.EMAIL = a.EMAIL)
    LEFT OUTER JOIN USERS_ARTICLES b
      ON (b.DATE = a.DATE)
    WHERE n.EMAIL IS NULL AND
          b.DATE IS NULL
    GROUP BY DATE, USER_ID

使用保留字 DATE 作为列名可能会导致问题 - 如果是这样,请将 DATE 括在双引号中(例如“DATE”)。

分享和享受。

于 2013-06-12T00:44:22.503 回答
1
INSERT INTO
  users_articles
  (date, user_id, hit_count)
SELECT
  uad.date,
  uad.user_id,
  SUM(uad.article_id) AS hits
FROM
  users_article_details uad
WHERE
  uad.email NOT IN (select email from do_not_email_user_table where email=uad.email) AND
  uad.date NOT IN (select `date` from users_articles where `date`=uad.date and user_id=uad.user_id)
GROUP BY
  uad.date,
  uad.user_id;
于 2013-06-11T20:27:31.887 回答