2014-03-27 12 views
0

所以我有兩個表。嘗試連接兩個表,將空字段顯示爲額外的行,並使這些空值0

select distinct id, doc 
from images 

它看起來像:

ID  | DOC 
-------------------- 
GROWG  APP 
GROWG  BACKGR 
MAXAR  APP 
MAXAR  BACKGR 
MAXAR  LIC 

select DriverID 
from drivers 

它看起來像

DriverID 
-------- 
GROWG 
ZULLY 
MAXAR 
JILLX 

我想要什麼我的最終結果的樣子時,我要麼使用一個臨時表或一個選擇語句就是使它成爲lo確定這樣的:

DriverID  |  Doc  |  Count 
----------------------------------------- 
GROWG    APP    1 
GROWG    BACKGR   1 
GROWG    LIC   **NULL** (or 0) 
MAXAR    APP    1 
MAXAR    BACKGR   1 
MAXAR    LIC    1 

所以它是識別存在共有3種不同類型的文件,它表明GROWG缺少他的文檔「LIC」

誰能幫助結束?

+0

驅動程序與結果有什麼關係? –

回答

2

我想你想是這樣的:

select id.id, doc.doc, count(i.id) as cnt 
from (select distinct id from images) as id cross join 
    (select distinct doc from images) doc left outer join 
    images i 
    on i.id = id.id and i.doc = doc.doc; 

它返回的iddoc所有組合從images,與計數表一起。如果組合不存在,它將返回0

編輯:

,檢查是否有匹配drivers,你可以添加:

where id in (select driverid from drivers) 
+0

謝謝,我明天再試一試,看看它是否有效。 –

+0

哦,我希望鏈接到它的驅動程序的原因是檢查驅動程序是否是employeed驅動程序。我忘了提及那部分。我將使用Driver表來檢查他們是否被僱傭,然後將其與圖片表進行比較,以查看他們缺失的圖片文件。 –

1

我修改從戈登·利諾夫上面的查詢。檢查此

select id.driverid, doc.doc, count(i.id) as cnt 
from (select distinct driverid from drivers) as id cross join 
    (select distinct doc from images) doc left outer join 
    images i 
    on i.id = id.driverid and i.doc = doc.doc 
    where id.driverid in (select id from images) 
    group by id.driverid,doc.doc; 
+0

這工作!謝謝。 –

+0

有沒有一種方法可以只選擇0值? –

+0

對於'GROWG'的0值,在group by子句後加上 (count)(i.id)= 0 。 – Sharad

相關問題