SQL Server,连接到具有相同列的多个表

问题描述 投票:1回答:2

使用SQL服务器,我有一个表可以使用同一列连接多个表。该表有两列,SourceType和SourceID。 SourceType是要加入的表,SourceID是我们加入的表的主键。这会生成如下查询:

select * 
from MyTable join TableOne
where MyTable.SourceId = TableOne.ID
   and MyTable.SourceType = 'TableOne';

select * 
from MyTable join TableTwo
where MyTable.SourceId = TableOne.ID
   and MyTable.SourceType = 'TableTwo';

我需要对此进行一些研究。这种方法叫什么?

sql sql-server database
2个回答
2
投票

如果我理解正确,您尝试使用一列来引用2个不同表的主键。我相信这种方法被称为polymorphic associations。这个概念是有效的,但使用您的解决方案来实现它并不是最好的方法。 Here's some other ways to do it.


0
投票

我想你想要这样的东西:

Select *
FROM Mytable AS myt
RIGHT JOIN TableOne AS tb1 ON myt.SourceId = tb1.ID

SELECT *
FROM MyTable AS myt
RIGHT JOIN TableTwo AS tb2 ON myt.SourceId = tb2.ID

您可以在这里找到更多细节:https://www.w3schools.com/sql/sql_join.asp

© www.soinside.com 2019 - 2024. All rights reserved.