1

假设我有一张桌子,

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)

我将如何进行查询,以便将 ParentTypeIDs 替换为 ParentTypeIDs 指向的 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。

4

2 回答 2

2

尝试这个

SELECT e.ID, p.Name, e.ParentTypeID
FROM [dbo].[EntityType] e
INNER JOIN [dbo].[EntityType] p ON e.ParentTypeID = p.ID
于 2013-09-18T15:45:31.340 回答
2
select  et1.ID,
        et1.Name,
        et2.Name as ParentName
from    dbo.EntityType et1 join dbo.EntityType et2 on et1.ParentTypeID = et2.ID
于 2013-09-18T15:40:02.800 回答