简体   繁体   English

MySQL外连接与连接表具有多个表的依赖关系

[英]MySQL outer-join with joined-table having dependencies to more than one table

I have 3 tables A, B and T 我有3张桌子A,B和T.

T holds a foreign key to table A and B respectively. T分别持有表A和B的外键。

Now I would like to get all rows of (A,B,T) even if T is empty. 现在我想获得(A,B,T)的所有行,即使T为空。

SELECT * from

A
LEFT OUTER JOIN T t1 ON t1.A_ID = A.id,
B
LEFT OUTER JOIN T t2 ON t2.B_ID = B.id

WHERE A.B_ID = B.ID

Now the problem is that I get too many rows so I add the following: 现在问题是我得到太多行,所以我添加以下内容:

AND t1.id = t2.id

But now I get no rows at all which I tried to avoid in the first place via including the LEFT OUTER JOIN. 但是现在我完全没有通过包括LEFT OUTER JOIN来避免排在第一位的行。

EDIT: Apart from any sample-data or table-layout my question is merely if a table T with foreign-key-dependencies to more than ONE table in this case A + B needs 2 left-outer-joins as given above or maybe there is another way? 编辑:除了任何样本数据或表格布局,我的问题仅仅是如果一个表T具有外键关键字依赖于多于一个表在这种情况下A + B需要2个左外连接,如上所述或者可能存在另一种方式?

Simply refering to table A in the second left-join like some users suggested cannot work as it is out-of-scope, also explained here 简单地在第二个左连接中引用表A就像一些用户建议的那样无法工作,因为它超出了范围, 这里也解释
So it works if you surround both tables with parens: 所以如果用parens包围两个表,它就可以工作:

SELECT * from (A, B)
LEFT OUTER JOIN T t ON t.A_ID = A.id and t.B_ID = B.id

Try 尝试

select *
from A
join B on A.B_ID = B.ID
left join T on T.A_ID = a.id and T.B_ID = b.id

.. assuming I've understood your question correctly, and you intend a regular, inner join between A and B 假设我已经正确地理解了你的问题,并且你打算在A和B之间进行常规的内部联接

Try this query: If A and B no any relation: 试试这个查询:如果A和B没有任何关系:

SELECT * FROM
(A, B)
LEFT OUTER JOIN T ON T.A_ID = A.id
AND T.B_ID = B.id

And if A and B have relation add this line at last: 如果A和B有关系,最后添加这一行:

WHERE A.B_ID = B.ID

If I've understood right, then maybe this will work for you? 如果我理解得对,那么也许这对你有用吗?

SELECT * from
A
LEFT OUTER JOIN T t1 ON t1.A_ID = A.id,
B
LEFT OUTER JOIN T t2 ON (t2.B_ID = B.id AND t1.id = t2.id)

WHERE A.B_ID = B.ID

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

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