来自同一个表的多个INNER JOIN

时间:2012-02-21 00:23:58

标签: sql sqlite join inner-join

我有一张金属表

MetalID    integer
MetalName  text
MetalCode  text

项目表

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

我正在尝试选择三个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=?

看起来我完全错了。请帮忙。

4 个答案:

答案 0 :(得分:26)

您应该为表指定不同的别名。你打电话给他们所有人。

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=?

答案 1 :(得分:8)

嗯,不是完全错误。 ;)

无论您拥有“INNER JOIN Metals AS m ”,m都必须是独一无二的(每次都不是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=?

答案 2 :(得分:2)

试试这个:

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

答案 3 :(得分:1)

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=?

或更简单但每行获得一个金属码

SELECT MetalCode
FROM Item
WHERE metalID = metal1 OR metalID = metal2 OR metalID = metal3