Link to home
Start Free TrialLog in
Avatar of chuang4630
chuang4630

asked on

How to do self join?

Table: Assets (AssetID, ReplacedByAssetID, PartNumber)
Table: Products(PartNumber, PartDesc)
ReplacedByAssetID allowed nulls. It may or may not have the value (int)
How do I construct a query to display:

AssetID, PartNumber, ReplacedByAssetID, ReplacedByPartNumber, ReplacedByPartDesc

Avatar of PamelaFluente
PamelaFluente

Here is a simple example.
http://www.technicalinterview.info/what-is-a-self-join-explain-it-with-an-example/

you just join a table with itself, by using an alias.

If you want to do it through a graphic ide (free) you can download this program:
http://www.datatime.eu/download.aspx
(a visual query builder)

-Pam




SELECT     a.AssetID, a.ReplacedByAssetID, ra.PartNumber, p.PartDesc
FROM         Assets ra
INNER JOIN
    Assets a ON ra.AssetID = a.ReplacedByAssetID
INNER JOIN
    Products p ON ra.PartNumber = p.PartNumber
Table: Assets (AssetID, ReplacedByAssetID, PartNumber)
Table: Products(PartNumber, PartDesc)
ReplacedByAssetID allowed nulls. It may or may not have the value (int)
How do I construct a query to display:

AssetID, PartNumber, ReplacedByAssetID, ReplacedByPartNumber, ReplacedByPartDesc

SELECT A.ASsetID, A.PartNumber,RA.ReplacedAssetID,P.PartDesc
FROm Assets A
INNERT JOIN Asset RA ON Ra.AssetID = RA.ReplacedAssetID
INNER JOIN Products P ON P.PartNumer = A.PartNumber
Avatar of David Todd
Hi,

... should this be ?
SELECT
  A.ASsetID
  , A.PartNumber
  , RA.ReplacedAssetID
  , RA.PartNumber
  , P.PartDesc
FROm Assets A
INNERT JOIN Asset RA ON RA.AssetID = A.ReplacedAssetID
INNER JOIN Products P ON P.PartNumer = RA.PartNumber

Regards
  David
Avatar of chuang4630

ASKER

Can we do the left join?

SELECT
  A.ASsetID
  , A.PartNumber
  , RA.ReplacedAssetID
  , RA.PartNumber
  , P.PartDesc
FROm Assets A
left JOIN Asset RA ON RA.AssetID = A.ReplacedAssetID
INNER JOIN Products P ON P.PartNumer = RA.PartNumber
Hi,

>> Can we do the left join?

Certainly.

What results do you get?

Regards
  David
ASKER CERTIFIED SOLUTION
Avatar of D B
D B
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial