Multiple INNER JOIN from the same table

NCFUSN picture NCFUSN · Feb 21, 2012 · Viewed 43.3k times · Source

I have a table of metals

MetalID    integer
MetalName  text
MetalCode  text

Item table

ItemID     integer
ItemName   text
...
Metal1     int Ref.-> metals.metalID
Metal2     int Ref.-> metals.metalID
Metal3     int Ref.-> metals.metalID

I am trying to select three MetalCodes

SELECT m.MetalCode as 'Metal1', m.MetalCode as 'Metal2',m.MetalCode as 'Metal3'
FROM Item as k
INNER JOIN Metals AS m ON m.metalID=k.metal1 
INNER JOIN Metals AS m ON m.metalID=k.metal2
INNER JOIN Metals AS m ON m.metalID=k.metal3
WHERE k.ItemID=?

Looks like I am doing it completely wrong. Please, help.

Answer

Beatles1692 picture Beatles1692 · Feb 21, 2012

You should specify different aliases for your tables . you are calling all of them m.

SELECT m1.MetalCode as 'Metal1', m2.MetalCode as 'Metal2',m3.MetalCode as 'Metal3'
FROM Item as k
INNER JOIN Metals AS m1 ON m1.metalID=k.metal1 
INNER JOIN Metals AS m2 ON m2.metalID=k.metal2
INNER JOIN Metals AS m3 ON m3.metalID=k.metal3
WHERE k.ItemID=?