简体   繁体   English

SQL Join-同一张表中的两个外键引用一个主键

[英]SQL Join - two foreign keys in the same table reference a primary key

I have two tables, one is a product transforming history table and the other is the products table: 我有两个表,一个是产品转换历史记录表,另一个是产品表:

dbo.Product_Change_History dbo.Product_Change_History

Date  FK_ProductID FK_FinalProductID ChangedBy
20160709    1               3           John

dbo.Product_Detail dbo.Product_Detail

PK_ProductID ProductName 
     1        Red Bike
     3        Green Bike

I would like a table like: 我想要一张像这样的桌子:

 Date      ProductName FinalProductName
20160709   Red Bike     Green Bike

How do I join the two tables to achieve this? 我如何结合两个表来实现这一目标? edit: This is in TSQL 编辑:这是在TSQL中

You'd have to join twice, which means you to alias at least one of the joins: 您必须加入两次,这意味着您至少要为其中一个加入别名:

SELECT Date, foo.ProductName, bar.FinalProductName
FROM Product_Change_history
LEFT JOIN Product_Detail AS foo ON fk_productid = foo.pk_productid
LEFT JOIN Product_Detail AS bar ON fk_finalproductid = bar.pk_productid

I'm not sure about LEFT joins VS INNER. 我不确定LEFT是否加入VS INNER。 I would think this would work well. 我认为这会很好。

SELECT
 link.Date,
 old.ProductName,
 new.ProductName as FinalProductName
FROM
 dbo.Product_Detail as old
 INNER JOIN dbo.Product_Change_History as link
  ON old.PK_ProductID = link.FK_ProductID
 INNER JOIN dbo.Product_Detail as new
  ON new.PK_ProductID = link.FK_FinalProductID
declare @ProdChange table(ProductID int, FK_ProductID INT, FK_FinalProductID INT, ChangedBy Varchar(100))

declare @Prod table(ProductID int, ProductName Varchar(100))

insert into @Prod Values(1,'Red Bike')
insert into @Prod Values(3,'Green Bike')

insert into @ProdChange Values(1,1,3,'John')
select * from @Prod
select * from @ProdChange

SELECT 
 old.ProductName,
 new.ProductName as FinalProductName
FROM
 @Prod as old
 INNER JOIN @ProdChange as link
  ON old.ProductID = link.FK_ProductID
 INNER JOIN @Prod as new
  ON new.ProductID = link.FK_FinalProductID

Thank you for the responses, with the help Chad Zinks answer I came to the correct solution: 感谢您的答复,在Chad Zinks的帮助下,我找到了正确的解决方案:

select
PRDHIST.Date,
OLDPROD.ProductName,
NEWPROD.ProductName
from dbo.Product_ChangeHistory PRDHIST
inner join dbo.Product_Detail OLDPROD
on OLDPROD.PK_ProductID = PRDHIST.FK_ProductID
inner join dbo.Product_Detail NEWPROD
on NEWPROD.PK_ProductID = PRDHIST.FK_FinalProductID;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM