简体   繁体   中英

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

Date  FK_ProductID FK_FinalProductID ChangedBy
20160709    1               3           John

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

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. 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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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