我工作了几个小时,只是为了得到我想要的SQL代码的结果,但没有运气。我正在尝试从一个表中选择所有记录并匹配其他表中的记录。
请参阅实时样本https://ucwa.skype.com/websdk。
url_id short_url campaign Clicks
1 test1 campaign1 2
2 test2 campaign2 2
上面示例中的SQL代码:
SELECT u.url_id, u.short_url, c.campaign, Count(*) AS Clicks
FROM (urls u LEFT JOIN log l ON l.url_id = u.url_id) LEFT JOIN campaign c ON u.campaign_id = c.campaign_id
WHERE (((DATE_FORMAT(l.date_time, '%Y-%m-%d')) Between '2017-03-14' And '2017-03-17'))
GROUP BY u.url_id, u.short_url, c.campaign;
我想要的结果就是这个。包括来自网址表的所有记录。
url_id short_url campaign Clicks
1 test1 campaign1 2
2 test2 campaign2 2
3 test3 campaign1 0
4 test4 0
我尝试在WHERE子句中添加l.url_id is null
,但点击的值为1而不是零(0)
url_id short_url campaign Clicks
1 test1 campaign1 2
2 test2 campaign2 2
3 test3 campaign1 1
4 test4 1
上面示例中的SQL代码:
SELECT u.url_id, u.short_url, c.campaign, Count(*) AS Clicks
FROM (urls u LEFT JOIN log l ON l.url_id = u.url_id) LEFT JOIN campaign c ON u.campaign_id = c.campaign_id
WHERE (((DATE_FORMAT(l.date_time, '%Y-%m-%d')) Between '2017-03-14' And '2017-03-17')) or l.url_id is null
GROUP BY u.url_id, u.short_url, c.campaign;
答案 0 :(得分:2)
使用COUNT(l.id)
代替COUNT(*)
。
在l.date_time IS NULL
子句中添加WHERE
。
检查http://rextester.com/YOX73980
SELECT u.url_id, u.short_url, c.campaign, Count(l.id) AS Clicks
FROM urls u
LEFT JOIN log l ON l.url_id = u.url_id
LEFT JOIN campaign c ON u.campaign_id = c.campaign_id
WHERE l.date_time IS NULL OR (DATE_FORMAT(l.date_time, '%Y-%m-%d')) Between '2017-03-14' And '2017-03-17'
GROUP BY u.url_id, u.short_url, c.campaign;
答案 1 :(得分:2)
在log
表上聚合可能在概念上更容易,因为这是生成点击次数的原因,而不是其他表。沿着这些方向,我们可以尝试以下查询:
SELECT t1.url_id,
t1.short_url,
COALESCE(t2.campaign, 'NA') AS campaign,
COALESCE(t3.num_clicks, 0) AS Clicks
FROM urls t1
LEFT JOIN campaign t2
ON t1.campaign_id = t2.campaign_id
LEFT JOIN
(
SELECT url_id, COUNT(*) AS num_clicks
FROM log
WHERE DATE_FORMAT(date_time, '%Y-%m-%d') BETWEEN '2017-03-14' AND '2017-03-17'
GROUP BY url_id
) t3
ON t1.url_id = t3.url_id;
<强>输出:强>
在这里演示:
答案 2 :(得分:1)
SELECT u.url_id, u.short_url, c.campaign, Count(c.campaign_id) AS Clicks
FROM urls u LEFT JOIN log l ON l.url_id = u.url_id
LEFT JOIN campaign c ON u.campaign_id = c.campaign_id
AND (((DATE_FORMAT(l.date_time, '%Y-%m-%d')) Between '2017-03-14' And '2017-03-17'))
GROUP BY u.url_id, u.short_url, c.campaign;
检查Demo