我有四张桌子,照片,事件,新闻,现场和照片是我想要检查与其他桌子有关系的记录的表格。
照片有以下结构:
id
rel_model -> one of "news", "spot" and "event"
rel_id -> id of the related record in rel_model table
...
Photo以外的表格会不断更新,有些记录会被删除。我想过滤照片以获取与其他表上的现有记录相关的记录。
我尝试了以下
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") ;
我需要在内连接之间添加一些和/或逻辑,位无法弄清楚如何。
如何获取与其他表格仍有完整关系的照片?
答案 0 :(得分: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
您的查询返回空行,因为您尝试将所有三个表连接到同一行,但是您的连接条件只匹配一个,因此其他两个内连接会消除您的行。
答案 1 :(得分: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";