2013-10-24 52 views
0

我有2个表合并两个表

表1的数据,它有列

id 
sdate 
type 

类型列可以有2级值的事件或时间表我使用这个查询来获取事件总数的结果, scheudle

select date_format(sdate, '%m-%d-%Y') as sdate, sum(type ='event') as tevent , sum(type='schedule') as tschedule from table1 where sid ='1' group by (sdate); 

表2具有这些列

id 
title 
dtime 

,使他们既类似于工会使用我做了这样的事情

select date_format(dtime, '%m-%d-%Y') as sdate ,0 as tevent,0 as tschedule,count(id) as tlog from table2 where sid =1 group by (sdate) ; 

我有点迷惑,我怎么能在某种程度上得到两个表中的数据,如果日期是相同的,应该告诉我数据在一列中。

回答

1

尝试此(包括原始查询的某些校正):

select sdate, sum(tevent) as tevent, 
sum(tschedule) as tschedule, sum(tlog) as tlog 
from (
select date_format(sdate, '%m-%d-%Y') as sdate, 
sum(type='event') as tevent , 
sum(type='schedule') as tschedule, 
0 as tlog from table1 
group by sdate 
union 
select date_format(dtime, '%m-%d-%Y') as sdate , 
0 as tevent,0 as tschedule, 
count(id) as tlog from table2 
group by sdate 
) s group by sdate; 
+0

感谢,但tevent和tschedule值表中的数据总是得到递增等是0,但与此查询它表明1 – Uahmed

+0

我改变计算总和,它作品 sum(type ='event')as tevent,sum(type ='schedule')as tschedule – Uahmed

+0

啊我明白了,那很聪明。总和(如果...)应该这样做。 (不计算,确实) – Ashalynd