自指向外键查询名称不是ID

时间:2013-09-18 15:35:11

标签: sql foreign-keys foreign-key-relationship

假设我有一张桌子,

CREATE TABLE EntityType
(
    ID int NOT NULL PRIMARY KEY IDENTITY,
    Name varchar(25) NOT NULL,
    ParentTypeID int
)
ALTER TABLE EntityType ADD CONSTRAINT EntityType_ParentTypeID_FK FOREIGN KEY(ParentTypeID) REFERENCES EntityType(ID)

我如何进行查询,以便将ParentTypeID替换为ParentTypeID指向的Name字段? 我试过了,

SELECT [dbo].[EntityType].ID, [dbo].[EntityType].Name, [dbo].[EntityType].ParentTypeID
FROM [dbo].[EntityType]
INNER JOIN [dbo].[EntityType] ON [dbo].[EntityType].ParentTypeID = [dbo].[EntityType].Name

显然这是错误的,但我对如何引用指向自身的键一无所知。没有Join它可以工作,但就像我说我想用适当的名称替换ParentTypeID。

2 个答案:

答案 0 :(得分:2)

select  et1.ID,
        et1.Name,
        et2.Name as ParentName
from    dbo.EntityType et1 join dbo.EntityType et2 on et1.ParentTypeID = et2.ID

答案 1 :(得分:2)

试试这个

SELECT e.ID, p.Name, e.ParentTypeID
FROM [dbo].[EntityType] e
INNER JOIN [dbo].[EntityType] p ON e.ParentTypeID = p.ID