考虑下表:
tweets daterange
--------------------------- ----------------
tweet_id nyse_date class _date
--------------------------- ----------------
1 2011-03-12 2 2011-03-11
2 2011-03-12 1 2011-03-12
3 2011-03-12 1 2011-03-13
4 2011-03-12 1 2011-03-14
5 2011-03-12 0 2011-03-15
7 2011-03-13 1
8 2011-03-13 2
9 2011-03-13 3
10 2011-03-14 3
每条推文都分配了一个“类”,可以是 1、2 或 3。我需要了解数据范围内每天每个类的推文数量。因此,即使 and 上没有推文2011-03-11
,2011-03-15
我仍然需要将该日期包含在结果集中,如下所示:
nyse_date total class1 class2 class3
-----------------------------------------
2011-03-11 0 0 0 0
2011-03-12 5 3 1 0
2011-03-13 3 1 1 1
2011-03-14 1 0 0 1
2011-03-15 0 0 0 0
我尝试了以下查询,但它只是超时(它不应该因为数据库不是那么大):
SELECT
t.nyse_date,
COUNT(CASE WHEN t.nyse_date = d._date THEN 1 END) total,
SUM(t.class=1) as neu,
SUM(t.class=2) as pos,
SUM(t.class=3) as neg
FROM tweets t
CROSS JOIN
daterange d
GROUP BY t.nyse_date
ORDER BY t.nyse_date ASC
这是EXPLAIN
id select_type table type possible_keys key key_len ref rows Extra
---------------------------------------------------------------------------------------------------
1 SIMPLE d ALL NULL NULL NULL NULL 148 Using temporary; Using filesort
1 SIMPLE t ALL NULL NULL NULL NULL 560783 Using join buffer
我究竟做错了什么?是否有更有效的方法来确保包含 daterange 表中的所有日期?
edit
: 我也试过这个查询,但结果保持不变 - 它一直运行到超时。
SELECT
t.nyse_date,
COUNT(t.tweet_id) AS total,
SUM(t.class=1) AS neu,
SUM(t.class=2) AS pos,
SUM(t.class=3) AS neg
FROM tweets t
LEFT JOIN
daterange d
ON t.nyse_date = d._date
GROUP BY t.nyse_date
ORDER BY t.nyse_date ASC
这是EXPLAIN
id select_type table type possible_keys key key_len ref rows Extra
-------------------------------------------------------------------------------------------------
1 SIMPLE t ALL NULL NULL NULL NULL 560783 Using temporary; Using filesort
1 SIMPLE d ALL NULL NULL NULL NULL 148