我有以下几种类型的桌子
Allow Large Results
我想基于Feed类型从Feed表中获取所有用户Feed,即如果Feed类型为badge,则object_id将引用“徽章”表;如果Feed类型为Blog,则object_id将引用“ Post”表在单个查询中。
实现此目标的最佳方法是什么?
目前,我正在通过代码执行此操作,并且也正在工作。只是想增强它。
答案 0 :(得分:0)
使用左联接和coalesce
函数
select f.*,coalesce(b.badge_name,p.post_name),
coalesce(b.slug,p.post_type)
from feeds f
left join badge b on f.object_id=b.id
left join post p on f.object_id=p.id
答案 1 :(得分:0)
您应该使用left join
,但标志的类型应该是条件的一部分:
select f.*,
coalesce(b.badge_name, p.post_name) as name,
coalesce(b.slug, p.post_type) as type
from feeds f left join
badge b
on f.object_id = b.id and
f.type = 'badge' left join
post p
on f.object_id = p.id and
f.type = 'post';