2013-08-02 51 views
0

我有四張表,照片,事件,新聞,現貨和照片是我想檢查記錄與其他表的關係。過濾一個表與多個內部聯接對其他表

照片具有以下sructure:

比照片等
id 
rel_model -> one of "news", "spot" and "event" 
rel_id -> id of the related record in rel_model table 
... 

表不斷更新和一些記錄AR刪除。我想過濾照片以獲取與其他表格上的現有記錄相關的記錄。

我嘗試以下

select 
    count(*) 
from 
    Photo 
     inner join Event ON (rel_id = Event.id and rel_model="event") 
     inner join News ON (rel_id = News.id and rel_model="news") 
     inner join Spot ON (rel_id = Spot.id and rel_model="spot"); 

,但我得到0的結果,其中有嘗試它只是一個內部聯接作品針對單個表

select 
    count(*) 
from 
    Photo 
     inner join Event ON (rel_id = Event.id and rel_model="event") ; 

檢查我需要添加一些和或邏輯在內部連接之間,有點無法弄清楚如何。

我該如何獲取仍然與其他表格有完整關係的照片?

回答

2

,你可以使用此查詢

select 
    count(*) 
from Photo as P 
where 
    P.rel_model = "event" and P.rel_id in (select T.id from Event as T) or 
    P.rel_model = "news" and P.rel_id in (select T.id from News as T) or 
    P.rel_model = "spot" and P.rel_id in (select T.id from Spot as T) 

如果你想改變你的查詢,你應該使用left outer join:因爲你想加入同一行所有

select 
    count(*) 
from Photo as P 
    left outer join Event ON (rel_id = Event.id and rel_model="event") 
    left outer join News ON (rel_id = News.id and rel_model="news") 
    left outer join Spot ON (rel_id = Spot.id and rel_model="spot") 
where News.id is not null or Spot.id is not null or Event.id is not null 

您的查詢返回空行三張表,但你的連接條件只匹配一個,所以其他兩個內部連接消除你的行。

1

您可以使用外部連接來完成此操作。如果rel_id與三者中的任何一個匹配失敗(並且大概只匹配其中的一個,所以你失去了所有的行),那麼內部連接就會失去連續性。然後,您需要分別計算每一個:

select count(Event.id) + count(News.id) + count(Spot.id) 
from Photo p left join 
    Event 
    ON p.rel_id = Event.id and rel_model="event" left join 
    News 
    ON p.rel_id = News.id and rel_model="news" left join 
    Spot 
    ON p.rel_id = Spot.id and rel_model="spot"; 
相關問題