我有2个日期表格,时间戳格式, 我必须计算每周有多少记录......
...并且只在一个查询中得到结果......
所以我会用例子更好地解释它:
2表,第一个:
table name: visitor
ID | time | ref (now i put in fake timestamp in time column sorry)
--------------------
1 | 3455 | john
2 | 3566 | ted (week 40)
3 | 8353 | ted (week 38)
4 | 6673 | katy
5 | 6365 | ted (week 40)
6 | 4444 | john
7 | 3555 | ted (week 40)
和第二个(非常相似):
table name: users
ID | time | ref (now i put in fake timestamp in time column sorry)
--------------------
1 | 3455 | ted (week 41)
2 | 3566 | ted (week 42)
3 | 8353 | ted (week 40)
4 | 6673 | katy
5 | 6365 | ted (week 41)
6 | 4444 | john
7 | 3555 | ted (week 38)
8 | 6789 | ted (week 43)
我执行此查询并获得此结果:
SELECT WEEK(FROM_UNIXTIME(time)) AS week, COUNT( * ) AS tot
FROM visitor WHERE ref='ted' GROUP BY week
表结果#1
week | tot
----------
38 | 1
40 | 3
43 | 1
我为第二张桌子做了一些:
SELECT WEEK(FROM_UNIXTIME(time)) AS week, COUNT( * ) AS totuser
FROM users WHERE ref='ted' GROUP BY week
表结果#2
week | totuser
----------
38 | 1
40 | 1
41 | 2
42 | 1
但我想只用一个查询就可以得到这个结果:
week | tot | totusers
---------------------- (when both are 0 doent appear -like 39 for example-)
38 | 1 | 1
40 | 3 | 1
41 | 0 | 2
42 | 0 | 1
43 | 1 | 0
我知道我使用LEFT JOIN,GROUP BY和IFNULL,但我总是做错了,我无法弄清楚。
按WEEK desc命令
谢谢你的帮助。答案 0 :(得分:2)
从技术上讲,你想要的是full outer join
,但MySQL不支持。我使用union all
和group by
:
SELECT weeek, SUM(visitors) as visitors, SUM(users) as users
FROM ((SELECT WEEK(FROM_UNIXTIME(time)) AS week, COUNT( * ) AS visitors, 0 as users
FROM visitor
WHERE ref='ted'
GROUP BY week
) UNION ALL
(SELECT WEEK(FROM_UNIXTIME(time)) AS week, 0, COUNT( * )
FROM users
WHERE ref ='ted'
GROUP BY week
)
) w
GROUP BY week
ORDER BY week;
注意:与您的数据一样,这只会包含访问者或用户的周数。如果你想要两周都没有,最好从包含你想要的所有周数的表开始(某种日历表)。