将右外连接转换为左外连接sqlite

时间:2016-02-03 12:37:34

标签: android sqlite join

我需要为Sqlite设计一个查询 原始查询就像这样

 FROM            PhysicianActivity INNER JOIN
                     Activity ON PhysicianActivity.ActivityID = Activity.ID RIGHT OUTER JOIN
                     PhysicianFrequency ON PhysicianActivity.PhysicianID = PhysicianFrequency.PhysicianID AND Activity.LegalEntityID = PhysicianFrequency.LegalEntityID 

知道sqlite不支持RIGHT OUTER JOIN所以我坚持使用LEFT OUTER JOIN但我无法将此查询转换为LEFT OUTER JOIN

任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

大多数人更喜欢LEFT OUTER JOIN。在大多数情况下,以下内容是等效的:

FROM  PhysicianFrequency LEFT JOIN
      PhysicianActivity 
      ON PhysicianActivity.PhysicianID = PhysicianFrequency.PhysicianID LEFT JOIN
      Activity
      ON PhysicianActivity.ActivityID = Activity.ID AND
         Activity.LegalEntityID = PhysicianFrequency.LegalEntityID 

我建议您使用表别名,以便查询更容易编写和阅读:

FROM  PhysicianFrequency pf LEFT JOIN
      PhysicianActivity pa
      ON pa.PhysicianID = pf.PhysicianID LEFT JOIN
      Activity a
      ON pa.ActivityID = a.ID AND
         a.LegalEntityID = pf.LegalEntityID

答案 1 :(得分:0)

根据定义,right outer join将返回所有匹配的行和右表中的行(相对于运算符的位置)没有匹配。

由于您知道希望PhysicianFrequency表中的记录始终可用,因此该表应该是left outer join中的左表。

因此,完整的陈述将如下所示:

PhysicianFrequency left join PhysicianActivity 
on PhysicianActivity.PhysicianID = PhysicianFrequency.PhysicianID AND Activity.LegalEntityID = PhysicianFrequency.LegalEntityID
left join Activity 
on PhysicianActivity.ActivityID = Activity.ID