我有2个表日志和轨道,每个日志都有一个时间戳但现在名字不同我尝试获取给定商店每天的所有日志,同时获取我的轨道表中每天的曲目数量< / p>
SELECT DATE(clicktime), COUNT(shop)
FROM LOG
WHERE shop = "shop01"
AND (clicktime > DATE_SUB(NOW(), INTERVAL 30 DAY))
GROUP BY DATE(clicktime);
此查询每天收集日志表中的所有条目,结果类似于
--------------------------------
ClickTime | Clicks
--------------------------------
2014-12-25 | 342
--------------------------------
2014-12-24 | 232
--------------------------------
我在第二张桌子上获得了每天的销售额
SELECT DATE(last_change) as SaleTime, COUNT(shop) as sale
FROM tracks
WHERE shop = "dd01"
AND (last_change > DATE_SUB(NOW(), INTERVAL 30 DAY))
AND relevant = 1
GROUP BY DATE(last_change)
输出
--------------------------------
SaleTime | sales
--------------------------------
2014-12-25 | 42
--------------------------------
2014-12-24 | 32
--------------------------------
我想将这2个查询合并为一个,以获得类似
的输出-----------------------------------------
Time | sales | clicks
-----------------------------------------
2014-12-25 | 42 | 342
-----------------------------------------
2014-12-24 | 32 | 232
-----------------------------------------
我尝试使用Union作为子查询,但是这个因为不同的表结构
而无法工作有没有办法达到预期目的?
答案 0 :(得分:2)
试试这个:
SELECT A.clicktime, A.shopCnt, B.saleCount
FROM (SELECT DATE(clicktime) clicktime, COUNT(shop) AS shopCnt
FROM LOG
WHERE shop = "shop01"
AND (clicktime > DATE_SUB(NOW(), INTERVAL 30 DAY))
GROUP BY DATE(clicktime)
) AS A
INNER JOIN (SELECT DATE(last_change) AS SaleTime, COUNT(shop) AS saleCount
FROM tracks
WHERE shop = "dd01"
AND (last_change > DATE_SUB(NOW(), INTERVAL 30 DAY))
AND relevant = 1
GROUP BY DATE(last_change)
) AS B ON A.clicktime = B.SaleTime
答案 1 :(得分:1)
我强烈建议您使用union
所有方法而不是inner join
。如果您有没有销售或点击的天数,那么join
将删除记录:
SELECT date, SUM(sales) as sales, SUM(clicks) as clicks
FROM ((SELECT DATE(last_change) as date, COUNT(*) as sales, 0 as clicks
FROM tracks
WHERE shop = 'dd01' AND (last_change > DATE_SUB(NOW(), INTERVAL 30 DAY)) AND relevant = 1
GROUP BY DATE(last_change)
)
UNION ALL
(SELECT DATE(clicktime) as date, 0 as sales, COUNT(*) as clicks
FROM LOG
WHERE shop = 'shop01' AND (clicktime > DATE_SUB(NOW(), INTERVAL 30 DAY))
GROUP BY DATE(clicktime)
)
) d
GROUP BY date;