0

我有一个我想了解的查询。有人可以阐明此查询的详细信息吗?
我只ON在连接条件中使用过一个子句。这个有多个条件,LEFT JOIN很难理解。

INSERT INTO nop_tbl
          (q_date, community_id, newsletter_t, subscription_count)     
  SELECT date(now()), a.community_id, 
     a.newsletter_type, 
     count(a.subscriber_user_id)
   FROM
      newsletter_subscribers_main a
   LEFT OUTER JOIN nop_tbl b
       ON (a.community_id = b.community_id)
       AND (a.newsletter_type = b.newsletter_t)
       AND (a.created_at = b.q_date)
   WHERE b.q_date is null
   AND   b.mailing_list is null
GROUP BY a.community_id, a.newsletter_t, a.created_at
4

3 回答 3

2

你有你的解释:

查询的目的是计算每个(q_date, community_id, newsletter_t)in的订阅newsletter_subscribers_main并将结果写入nop_tbl.
防止行LEFT JOIN被多次添加。

但我也认为,查询效率低下,可能是错误的。

  • 第2WHERE条:

    AND   b.mailing_list is null
    

    只是噪音,可以去除。如果b.q_date is null, thenb.mailing_list在此查询中保证为空。

  • 您不需要围绕JOIN条件的括号。

  • 如果subscriber_user_id已定义NOT NULLcount(*)则相同,更便宜。

  • 我怀疑a.created_at在插入时按 ,分组date(now())可能是错误的。几乎没有任何意义。我有根据的猜测(假设created_at是 type date):

INSERT INTO nop_tbl
      (q_date, community_id, newsletter_t, subscription_count)     
SELECT a.created_at
      ,a.community_id
      ,a.newsletter_type
      ,count(*)
FROM   newsletter_subscribers_main a
LEFT   JOIN nop_tbl b ON a.community_id = b.community_id
                     AND a.newsletter_type = b.newsletter_t
                     AND a.created_at = b.q_date
WHERE  b.q_date IS NULL
GROUP  BY a.created_at, a.community_id, a.newsletter_t;
于 2013-06-17T16:36:27.277 回答
1

简短的版本是:

  1. insert ... select ...
    -> 查询正在填充nob_tbl
  2. from ...
    -> 基于数据newsletter_subscribers_main
  3. left join ... where ... is null
    -> 尚未出现在nob_tbl
于 2013-06-17T15:32:18.170 回答
0

一步步

INSERT INTO nop_tbl
      (q_date, community_id, newsletter_t, subscription_count) 

INSERT语法这是告诉数据库在哪个表和哪个列中将用于插入查询

SELECT date(now()), a.community_id, 
       a.newsletter_type, 
       count(a.subscriber_user_id)

这些是要插入的选定字段

FROM
newsletter_subscribers_main a

这是告诉数据库选择a.从表中附加别名的字段newsletter_subscribers_main

LEFT OUTER JOIN nop_tbl b

这是加入另一个表nop_tbl,其中将选择其他字段

ON (a.community_id = b.community_id)
AND (a.newsletter_type = b.newsletter_t)
AND (a.created_at = b.q_date)

这些是 的规则JOIN,实际上是在告诉哪些列将用于连接

WHERE b.q_date is null
AND   b.mailing_list is null

这些是WHERE子句,它们用于将结果限制为请求的数据,在这种情况下,两列为空

GROUP BY a.community_id, a.newsletter_t, a.created_at

GROUP BY子句,用于对给定列上的结果进行分组

您可以在此处对连接进行可视化解释

于 2013-06-17T15:30:03.673 回答