[英]Filtering one table with multiple inner joins against other tables
我有四张桌子,照片,事件,新闻,现场和照片是我想要检查与其他桌子有关系的记录的表格。
照片有以下结构:
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") ;
我需要在内连接之间添加一些和/或逻辑,位无法弄清楚如何。
如何获取与其他表格仍有不间断关系的照片?
你可以使用这个查询
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
您的查询返回空行,因为您尝试将所有三个表连接到同一行,但您的连接条件只匹配一个,因此其他两个内部连接将消除您的行。
您可以使用外连接执行此操作。 使用内部联接时,当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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.