2012-09-07 52 views
1

我有以下最低的模式在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 

用简单的英语我所寻找的是返回所有已知的猫+及其相关的猫源+他们的猫的状态,同时保留空值。我将获得的唯一信息是我很好奇的来源。我也只想

UPDATE

为了澄清猫的映射是这样说要么零散的或未知的(空)的状态的猫:

猫的ID存储在catId列下的Source表中。
状态表具有对标记为catSource的列的源PK的引用。

在实践中得到当前猫地位的查询是:

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 

回答

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

将提供'未知'的任意状态等于空吗? – Woot4Moo

+0

非常接近正确它提供了双倍的结果,虽然 – Woot4Moo

+0

我没有看到你的小提琴如何猫与地位和来源有关...如果我能想出来,我可以调整以上 – podiluska

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 
+0

这与我所期待的非常接近。输出中有第二个Steve条目。因为引用了其他来源。 – Woot4Moo