多连接查询返回许多结果并且不正确匹配

时间:2012-09-07 15:29:24

标签: sql database oracle

我在Oracle中有以下最小模式:http://sqlfiddle.com/#!4/c1ed0/14

我运行的查询会产生太多结果和此查询:

select cat.*, status.*, source.*
from cats cat, status status, source source
Left OUTER JOIN source source2
on source2.sourceid = 1
Right OUTER JOIN status status2
on status2.isStray =0
order by cat.name

会产生不正确的结果。我期待的是一个看起来像下面的表,但我似乎无法想出正确的SQL。

NAME    AGE     LENGTH  STATUSID    CATSOURCE   ISSTRAY     SOURCEID    CATID
 Adam    1        25     null         null         null       1             2
 Bill    5        1      null         null         null       null          null
 Charles 7        5      null         null         null       null          null
 Steve   12       15     1            1            1          1             1

简单的英语我要找的是在保留空值的同时返回所有已知的猫及其相关的猫源+猫的状态。我将获得的唯一信息是我很好奇的来源。我也只想要状态为STRAY或UNKNOWN(null)的猫

更新

为了澄清,Cats的映射如下:

Cat的id存储在catId列下的Source表中 Status表引用了Source of PK作为标记为catSource的列。

实际上,要获取当前cat的状态,查询将是:

select cat.* from cats cat, status status, source source  
where cat.id = source.catId  
and source.sourceId = status.catSource

最终查询

select *
from source
    inner join cats on source.catid = cats.id
and source.sourceid = 1
    left join status on source.sourceid = status.catsource

2 个答案:

答案 0 :(得分:1)

select *
from source
    inner join cats on source.catid = cats.id
    left join status on source.sourceid = status.catsource
         and statusid=1

答案 1 :(得分:1)

预期的数据似乎有些偏差。检查此查询(使用oracle语法)。

select c.name,
       c.age,
       c.length,
       s.*,
       src.*
  from cats c,
       status s,
       Source src
  where c.id = s.StatusId(+)
     and c.id = src.sourceId(+)
  order by c.name


Adam    1   25              2   2
Bill    5   1                   
Charles 7   5                   
Steve   12  15  1   1   1   1   2
Steve   12  15  1   1   1   1   1