2013-10-24 304 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