制定 TSQL 左连接
我正在使用 SSMS 2008。应该是一个简单的解决方案。我试图从表 A 中提取所有记录,但只从表 B 和 C 中提取匹配的记录。问题是,如果我保留连接表 B 和 C,它会返回所有 3 个表相交的记录。就像如果我查询这个组合合并,我会得到 B 和 C 的每一行的非 NULL 值。
这是我的伪代码:
SELECT A.ID, B.ID, C.ID
FROM A
LEFT JOIN B ON B.ID = A.ID
LEFT JOIN C ON C.ID = A.ID
在回答你的问题时,很抱歉我忘记了“LEFT”,但我只是在上面添加了它。如果表A有9行,B有2行,C有3行,那么我想在上面看到的是表A与B相交以及A与C相交的位置。 所以在刚才描述的场景中,假设表 B 的行与表 C 的行全部不同,那么我想看到总共 5 行; B 为 2,C 为 3。有意义吗?
I am using SSMS 2008. Should be a simple solution to this. I am trying to pull all records from table A, but only pull in matching records from tables B and C. The problem is that if I left join tables B and C, it returns records where all 3 of these tables intersect instead. Like if I query this combined merge, I get non-NULL values for every row for both B and C.
Here is my pseudocode:
SELECT A.ID, B.ID, C.ID
FROM A
LEFT JOIN B ON B.ID = A.ID
LEFT JOIN C ON C.ID = A.ID
In answer to your questions, I am sorry I forgot the "LEFT", but I just added it above. If table A has 9 rows and B has 2 rows and C has 3 rows, then what I want to see above is where table A intersects B and where A intersects C.
So in the scenario just described, assuming that the Table B rows are all different than the Table C rows, then I want to see a total of 5 rows; 2 from B and 3 from C. Make sense?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题陈述仍然不一致。我认为你的意思是表 A 与 B 相交或 A 与 C 相交。在这种情况下,正确的 TSQL 是:
如果 B.ID 和 C.ID 等于 A.ID,则无需报告它们。
Group By 是为了避免重复 A.ID。
The problem statement is still inconsistent. I think you mean where table A intersects B OR where A intersects C. In that case the proper TSQL is:
No need to report B.ID and C.ID if they equal A.ID.
Group By is so you don't get repeated A.ID.
或者,如果您只需要 A 中的字段,那么
Or, if you need only fields from A, then
实现此目的的理想方法是使用
LEFT JOIN
。我相信(尽管从您的问题中不清楚)您遇到的问题是每个A.ID
有多行。如果
A.ID
与B.ID
ANDC.ID
匹配,那么您将获得两行,并且想要一个合并行。我认为您的测试查询中可能混合了
JOIN
条件。这对我来说在测试中工作得很好。尝试以下查询:输出为:
The ideal way to do this is with a
LEFT JOIN
. I believe (though it's unclear from your question) that the problem you have is multiple rows perA.ID
.If
A.ID
matchesB.ID
ANDC.ID
then you are getting two rows for this, and would like one consolidated row.I think maybe you had your
JOIN
conditions mixed up in your test query. This is working fine for me in testing. Try the below query:Output is:
你想要的是加入工会声明。
what you want is a join to a union stamtement.