内部加入一张桌子对许多其他人

时间:2011-02-21 19:49:43

标签: sql sql-server database tsql

我有一个表 A ,其中包含列(Id,Value)
和一个表 B 与列(BId,Id,..) 以及带有列(CId,Id,...)

的表 C

我需要在这些表上执行内连接,如下所示

 select a.Id,a.Value from A a
 inner join B b on b.Id=a.Id
 inner join C c on c.Id=a.Id
 where <many conditions on table B and C>

我怎样才能达到同样的目标。现在我刚刚运行查询

 select a.Id,a.Value from A a
 inner join B b on b.Id=a.Id
 inner join C c on c.Id=a.Id

它没有返回任何东西..请帮助。

仅当我单独运行联接时,它会给我行。我只想要他们的联盟......

示例数据:

A
1
2
3

B
2

C
3

然后我想选择

A
2
3

提前致谢。

2 个答案:

答案 0 :(得分:1)

因此,根据您的评论,您似乎想要这样的内容:

select a.Id,a.Value from A a
 inner join B b on b.Id=a.Id
where <many conditions on table B>
UNION ALL
SELECT a.Id, a.Value from A
 inner join C c on c.Id=a.Id
 where <many conditions on table C>

答案 1 :(得分:0)

只要字段与A上的ID匹配 - >&gt; B和A - &gt; C并且您没有任何其他连接条件,您应该能够看到匹配的行。

我无法理解你关于B和C Id如何不匹配的观点。如果a.id = b.id和a.id = c.id,它是否自动暗示b.id = c.id?

无论如何,在这样的情况下,我尝试在B和C上进行A的外连接,看看我认为匹配的行是否确实存在。

select a.Id,a.Value from A a
 left outer join B b on b.Id=a.Id
 left outer join C c on c.Id=a.Id
 where (b.id is not null or c.id is not null) 
       /* Matching record found in b or c */

编辑:根据您的要求,您可以使用上面提到的Lamak方法(使用UNION Alls),或者如果您确定A中的每条记录,您只能使用一条记录B和C中最多只有一列,只能使用一列,您可以使用scalar sub query approach