[英]MySQL with ON condition from another table
Let's say that I have: 让我们说我有:
SELECT * FROM a
LEFT OUTER JOIN b ON b.a_id = a.id
LEFT OUTER JOIN c ON b.c_id = c.id
Now what I want to do is to select b's that are assigned to c that is eg active (c.active = 1). 现在我想要做的是选择分配给c的b,例如有效(c.active = 1)。 How can I do that with ON?
我怎么能用ON做到这一点?
Note that I can't use WHERE after the whole query above, because I want a's to be returned even if 0 b's are found. 请注意,我不能在上面的整个查询之后使用WHERE,因为即使找到0 b,我也想要返回。
Did you try something like this? 你尝试过这样的事吗?
SELECT * FROM a LEFT OUTER JOIN b ON b.a_id = a.id AND c.active = "1" LEFT OUTER JOIN c ON b.c_id = c.id AND c.active = "1" SELECT * FROM LEFT OUTER JOIN b ON b.a_id = a.id AND c.active =“1”LEFT OUTER JOIN c ON b.c_id = c.id AND c.active =“1”
Just to make sure, I understood the question: You want all rows where either c.active equals 1 or where there is no entry in b or c, right? 为了确保,我理解了这个问题:你想要所有行,其中c.active等于1或者b或c中没有条目,对吧?
It's a bit lengthy but this seems to work: 它有点冗长,但这似乎有效:
SELECT * FROM a
LEFT OUTER JOIN b ON a.aid = b.aid
LEFT OUTER JOIN c ON b.bid = c.bid
WHERE a.aid NOT IN (
SELECT a.aid FROM a
INNER JOIN b ON a.aid = b.aid
INNER JOIN c ON b.bid = c.bid
WHERE NOT c.active
);
I could also imagine a solution using UNION
我还可以想象使用
UNION
的解决方案
Which rows are returned in each case... Note that one case is different: 在每种情况下返回哪些行...请注意,一种情况不同:
FROM b JOIN c ON ... AND c.active=1
-- rows in both tables exist and active FROM b JOIN c ON ... AND c.active=1
- 两个表中的行都存在并处于活动状态
FROM b JOIN c ON ... WHERE c.active=1
-- ditto FROM b JOIN c ON ... WHERE c.active=1
- 同上
FROM b LEFT JOIN c ON ... WHERE c.active=1
-- ditto FROM b LEFT JOIN c ON ... WHERE c.active=1
- 同上
FROM b LEFT JOIN c ON ... AND c.active=1
-- all b's, but NULLs for inactive/missing c's FROM b LEFT JOIN c ON ... AND c.active=1
- 全部为b,但是非活动/缺失c的NULL
(Caveat: I am not sure I got the cases correct; just keep in mind that ON and WHERE are not always interchangeable.) (警告:我不确定我的案例是否正确;请记住,ON和WHERE 并不总是可以互换的。)
When mixing JOIN and LEFT JOIN, you may need to add parentheses: 混合JOIN和LEFT JOIN时,您可能需要添加括号:
FROM a JOIN ( b LEFT JOIN c ON... ) ON ... WHERE ...
FROM ( a JOIN b ON ... ) LEFT JOIN c ON... WHERE ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.