簡體   English   中英

SQL Server,聯接到具有同一列的多個表

[英]SQL Server, join to more than one table with the same column

使用SQL Server,我有一個表,可以使用同一列將多個表連接在一起。 該表有兩列,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';

我需要對此做一些研究。 這種方法叫什么?

如果我理解正確,則您嘗試使用一列來引用2個不同表的主鍵。 我相信這種方法稱為polymorphic associations 這個概念是有效的,但是使用您的解決方案來實施它不是最佳方法。 這是其他方法。

我想你想要這樣的東西:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM