左连接表并获取每个表的日期范围

时间:2015-05-20 12:06:44

标签: mysql sql left-join

我有以下查询:

    SELECT 
       t.aff_id,
       Ifnull(t.campaign_name, "direct") AS campaign_name,
       Count(t.uuid)                     AS visits,
       Count(DISTINCT l.trader_id)       AS leads
FROM   trackings AS t
       LEFT JOIN (SELECT uuid,
                         trader_id
                  FROM   leads
                  WHERE  aff_id = "1"
                         AND created_at BETWEEN "2015-05-01 00:00:00" AND
                                                "2015-05-20 23:59:59") AS l
              ON l.uuid = t.uuid

WHERE  `t`.`created_at` BETWEEN '2015-05-01 00:00:00' AND '2015-05-20 23:59:59'
       AND `t`.`aff_id` = '1'
GROUP  BY `t`.`campaign_name` 

潜在客户表日期范围没有影响,这样的查询应该是什么样的正确结构? http://sqlfiddle.com/#!9/5d125/2

1 个答案:

答案 0 :(得分:0)

我认为可以通过加入达到预期的结果:

SELECT
   t.aff_id,
   IFNULL(t.campaign_name, 'direct') AS campaign_name,
   COUNT(t.uuid) AS visits,
   COUNT(DISTINCT l.trader_id) AS leads
FROM trackings AS t
LEFT JOIN leads AS l
    ON l.uuid = t.uuid
    AND l.created_at BETWEEN '2015-05-01 00:00:00' AND '2015-05-20 23:59:59'
    AND aff_id = '1'
WHERE
    t.created_at BETWEEN '2015-05-01 00:00:00' AND '2015-05-20 23:59:59'
    AND t.aff_id = '1'
GROUP BY
    campaign_name
;