简体   繁体   English

如何在mysql中组合内部和外部联接

[英]How do you combine an inner and outer join in mysql

I can do it in sybase and I can do it in oracle, but I'm not seeing how to do it in mysql. 我可以在sybase中完成它,我可以在oracle中完成它,但我没有看到如何在mysql中完成它。

I've got this: (please restrain yourself from re-formatting my sql, last time somebody did that they changed it so it wasn't the same and made the question meaningless) 我有这个:(请限制自己重新格式化我的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')

And I get all sorts of results that make no sense. 而且我得到了各种没有意义的结果。

I want to get a list of all of the id's from table1 where table2.data = cat, then do an outer join with the results of that against table 3 where table3.data = dog. 我想得到table1中所有id的列表,其中table2.data = cat,然后对表3执行外连接,其中table3.data = dog。

I notice that I can't specify the same table/alias for table1 in the two join clauses, so that leads me to believe that mysql is running the join expressions separately and ORing the results together or something like that. 我注意到我无法在两个join子句中为table1指定相同的表/别名,因此这让我相信mysql分别运行连接表达式并将结果或其他东西进行OR运算。

I also tried getting rid of the "inner join" in the from section and putting it in the where clause, that didn't work either, though it didn't work in a different way (got different erroneous results) 我也尝试摆脱from部分中的“内部联接”并将其放在where子句中,这也不起作用,尽管它不能以不同的方式工作(得到不同的错误结果)

This would be so easy in sybase or oracle. 这在sybase或oracle中会非常容易。

What am I doing wrong? 我究竟做错了什么?

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')

I think you never want to use a comma in the from statement. 我想你永远不想在from语句中使用逗号。 I believe the comma is equivalent to saying cross join. 我相信逗号相当于说交叉连接。 Not sure though, but I think this query is what you're looking for. 虽然不确定,但我认为这个查询是您正在寻找的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM