日期:2014-05-16  浏览次数:20448 次

sql语言 一个表中两个字段都是同一个外键,怎么取到外键表的表项
 ---生成一个视图 想在视图中把BranchName对应出来,而不是ID
CREATE VIEW dbo.v_listAllocOut
AS
SELECT 
      dbo.CK_AllocOut.CK_AllocOutDate
, dbo.CK_AllocOut.CK_AllocOutNo
, CK_Branch.CK_BranchName    outbranch
, CK_Branch.CK_BranchName tobranch
FROM CK_AllocOut
inner JOIN dbo.CK_Branch ON dbo.CK_Branch.CK_BranchID = CK_AllocOut.CK_OutBranchID
inner JOIN dbo.CK_Branch ON dbo.CK_Branch.CK_BranchID = CK_AllocOut.CK_ToBranchID
-----上面会报错,无法通过------

CK_AllocOut表如下:
CREATE TABLE dbo.CK_AllocOut(
  CK_AllocOutID   INT IDENTITY NOT NULL  PRIMARY KEY NONCLUSTERED,
  CK_AllocOutDate DATETIME NOT NULL DEFAULT '',
  CK_OutBranchID  INT NOT NULL  FOREIGN KEY REFERENCES CK_Branch(CK_BranchID), 
  CK_ToBranchID   INT NOT NULL FOREIGN KEY REFERENCES CK_Branch(CK_BranchID),
  CK_AllocOutPeople     VARCHAR(32) NOT NULL DEFAULT '', 
);
------解决方案--------------------
SELECT 
      a.CK_AllocOutDate       
    , a.CK_AllocOutNo
    , outbranch  --这两个字段你对应看是b还是c表的
    , tobranch --这两个字段你对应看是b还是c表的
FROM CK_AllocOut a
inner JOIN dbo.CK_Branch b ON a.CK_BranchID = b.CK_OutBranchID
inner JOIN dbo.CK_Branch c ON a.CK_BranchID = c.CK_ToBranchID