如何在左连接分支内强制连接?
我需要 LEFT 连接到整个 t2+t3 分支,但是如果我可以找到 t1 和 t2 之间的匹配连接,我想强制执行 t2 和 t3 连接。
SELECT T1.name,T2.bob,T3.a
FROM T1
LEFT JOIN T2 ON t1.id = t2.t1_id
JOIN T3 ON t2.id = T3.t2_id
语法是什么?
样本数据:
T1 [id,name]
1 aaa
2 bbb
3 ccc
T2 [id,t1_id,bob]
1,1,777
2,1,888
2,2,999
T3[id,t2_id,a]
1,2,'yeh'
预期结果:
[name] , [a] , [bob]
aaa , 'yeh' , 888
bbb , NULL , NULL
ccc , NULL , NULL
I need to LEFT join to entire t2+t3 branch, but if I can find a matching join between t1 and t2, I want to enforce the t2 and t3 join.
SELECT T1.name,T2.bob,T3.a
FROM T1
LEFT JOIN T2 ON t1.id = t2.t1_id
JOIN T3 ON t2.id = T3.t2_id
What is the syntax?
Sample data:
T1 [id,name]
1 aaa
2 bbb
3 ccc
T2 [id,t1_id,bob]
1,1,777
2,1,888
2,2,999
T3[id,t2_id,a]
1,2,'yeh'
EXPECTED RESULT:
[name] , [a] , [bob]
aaa , 'yeh' , 888
bbb , NULL , NULL
ccc , NULL , NULL
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑:此查询返回示例数据中预期的结果 -
(另请注意,此查询是在下面 Treefrog 的答案的帮助下进行的) -
我的旧答案 -
EDIT: This query returns you the result as expected from your sample data -
(Also note, this query is taken with help from Treefrog's answer below) -
My Older answer -
这两个都会给你结果。不确定哪个会表现更好。
嵌套语句:
临时表:
Both of these will give you your result. Not sure which would perform better.
NESTED STATEMENT:
TEMPORARY TABLE:
这应该适用于 MySQL
This should work in MySQL