基于同一列加入

时间:2011-07-14 05:47:45

标签: sql sql-server-2005 sql-server-2008 sql-server-2000 inner-join

我有两个表,例如TableA和TableB。

TableA的架构:

     UoMID
     UoMName

TableB的架构:

     ItemID
     ItemName
     UoMID
     D1_UoMID
     D2_UoMID
     D3_UoMID

这里我想基于TableA中的UoMID和TableB中的UoMID,D1_UoMID,D2_UoMID和D3_UoMID来加入这两个表。 我想检索以下列:

     ItemName, UoMName, D1_UoMName, D2_UoMName and D3_UoMName

如何检索上面的列?如何识别对应的UoMID,D1_UoMID,D2_UoMID和D3_UoMID的UoMName?

3 个答案:

答案 0 :(得分:3)

使用aliases,您可以多次加入同一个表,并区分不同联接的结果。试试这个:

SELECT
    ItemName,
    d0.UoMName,
    d1.UoMName as D1_UoMName,
    d2.UoMName as D2_UoMName,
    d3.UoMName as D3_UoMName
from TableB tb
join TableA d0 on d0.UoMID = tb.UoMID
join TableA d1 on d1.UoMID = tb.D1_UoMID
join TableA d2 on d2.UoMID = tb.D2_UoMID
join TableA d3 on d3.UoMID = tb.D3_UoMID;

答案 1 :(得分:2)

SELECT ta.UoMName, ta1.UoMName, ta2.UoMName ta3.UoMName 
FROM TableA AS ta, TableA AS ta1, TableA AS ta2, TableA AS ta3, TableB AS tb
WHERE ta.UoMID = tb.UoMID
AND ta.UoMID = tb.UoMID
AND ta1.UoMID = tb.D1_UoMID
AND ta2.UoMID = tb.D2_UoMID
AND ta3.UoMID = tb.D3_UoMID

如果要多次使用同一个表,则必须为表提供别名。

答案 2 :(得分:1)

SELECT 
     b.ItemName,
     (SELECT a1.UoMName FROM TableA a1 WHERE a1.UoMID = b.UoMID) as UoMName,
(SELECT a2.UoMName FROM TableA a2 WHERE a2.UoMID = b.D1_UoMID) as D1_UoMName,
(SELECT a3.UoMName FROM TableA a3 WHERE a3.UoMID = b.D1_UoMID) as D3_UoMName,
(SELECT a4.UoMName FROM TableA a4 WHERE a4.UoMID = b.D1_UoMID) as D3_UoMName,
FROM TableB b

希望这有效