2009-01-08 94 views
4

我可以在sybase中完成,我可以在oracle中完成,但是我没有看到如何在mysql中完成它。如何在mysql中结合内连接和外连接

我有这样的: (请克制自己从重新格式化我的SQL,最后一次有人这样做,他们改变了它,所以它是不一样的,并提出问题毫无意义)

select table1.id 
from 
table1 
    inner join 
    table2 on (table1.id = table2.id and table2.data='cat'), 
table1 t1 
    left outer join 
    table3 on (t1.id = table3.id and table3.data = 'dog') 

我得到各种毫无意义的结果。

我想从table1中获取所有id的列表,其中table2.data = cat,然后对table3的数据进行外部连接,其中table3.data = dog。

我注意到我无法为两个连接子句中的table1指定相同的表/别名,所以这使我相信mysql正在单独运行连接表达式,并将结果或在一起或类似的东西。

我也尝试摆脱了从内部的“内部连接”,并把它放在where子句,即使没有工作,虽然它没有以不同的方式工作(得到不同的错误结果)

这在sybase或oracle中会很容易。

我在做什么错?

回答

13
select table1.id 
from 
table1 
    inner join 
    table2 on (table1.id = table2.id and table2.data='cat') 
    left outer join 
    table3 on (table1.id = table3.id and table3.data = 'dog') 

我想你永远不想在from语句中使用逗号。我相信逗号相当于说交叉连接。虽然不确定,但我认为这个查询就是你要找的。

+0

使用逗号语法,通常情况下,您可以通过在WHERE子句中添加条件来防止它成为交叉连接。 – 2009-01-08 05:34:09