加入ON日期组

时间:2011-04-27 05:34:34

标签: mysql sql join aggregate-functions

我有3张桌子;

表1

id   date
1    1132123123
2    1232342341

etc

表2

id   date
1    1132123123
2    1232342341

etc

表3

id   date
1    1132123123
2    1232342341

etc

所有“日期”列都是unix时间戳。

我正在尝试加入这3个表并计算每个表的总计数,分别按:

分组
FROM_UNIXTIME(date, '%m-%d-%Y')

理想情况下,我想要这个结果:

formatteddate   t1count   t2count   t3count
04-12-2011      2         2         2
04-13-2011      1         2         3

注意:结果与示例数据不符,但我认为这很简单。

这是我到目前为止所尝试的内容:

SELECT
  FROM_UNIXTIME(t1.date, '%m-%d-%Y') as t1date,
  FROM_UNIXTIME(t2.date, '%m-%d-%Y') as t2date,
  FROM_UNIXTIME(t3.date, '%m-%d-%Y') as t3date, 
  count(t1.id) as t1count,
  count(t2.id) as t2count,
  count(t3.id) as t3count
FROM
  t1,t2,t3
GROUP BY
  t1date

查询甚至没有加载。 t3包含大量数据(100万条+记录)。 t1& t2,不是那么多。

1 个答案:

答案 0 :(得分:3)

select from_unixtime(date,'%m-%d-%Y') as d,
sum(tb=1) as tb1,
sum(tb=2) as tb2,
sum(tb=3) as tb3
from (
select date,1 as tb from t1
union all
select date,2 from t2
union all
select date,3 from t3) as t
group by d