1

我有四个表,照片、事件、新闻、现场和照片是我要检查与其他表关系的记录的表。

照片具有以下结构:

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

除了照片之外的表格会不断更新,并且一些记录会被删除。我想过滤照片以获取与其他表上现有记录相关的记录。

我尝试了以下

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") ;

我需要在内部连接之间添加一些和/或逻辑,有点不知道怎么做。

如何获取与其他表仍然有完整关系的照片?

4

2 回答 2

3

你可以使用这个查询

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

您的查询返回空行,因为您尝试将同一行与所有三个表连接,但您的连接条件仅匹配一个,因此其他两个内部连接消除了您的行。

于 2013-08-02T22:13:01.377 回答
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"; 
于 2013-08-02T22:16:56.593 回答