TSQL什么是执行这个微小SELECT查询的最简单方法?

时间:2012-05-23 19:16:19

标签: tsql select

我正试图找出执行某些查找的最简洁方法。我在这里有一个满是员工的索引表,然后是一个更大的票证表,它在几个地方使用他们的EmployeeID--谁制作票证,最后更新票证,谁关闭它。我试图弄清楚在SELECT查询中提取每个名字的最简单方法,而不是每次都做一个小子查询,这就是我现在正在做的事情。

我为自己做了一个小练习,试图简化这个问题:

    CREATE TABLE NameLookup
    (
        NameIndex INT PRIMARY KEY CLUSTERED IDENTITY(1,1),
        Name VARCHAR(10)
    );

    CREATE UNIQUE NONCLUSTERED INDEX NameIdx ON dbo.NameLookup ([Name])
    WITH (IGNORE_DUP_KEY = OFF);

    CREATE TABLE BunchaNames
    (
        PK INT PRIMARY KEY CLUSTERED IDENTITY(1,1),
        NameOne INT FOREIGN KEY REFERENCES dbo.NameLookup(NameIndex),
        NameTwo INT FOREIGN KEY REFERENCES dbo.NameLookup(NameIndex),
        NameThree INT FOREIGN KEY REFERENCES dbo.NameLookup(NameIndex)
    );

    INSERT INTO NameLookup(Name)
    VALUES ('Bill'), ('Phil'), ('Jill'), ('Gil'), ('Fred');

现在,我想从BunchaNames中选择SELECT NameOne,NameTwo和NameThree,并在NameLookup中显示名称。这是最简单/最正确的方法吗?是这个吗?非常感谢您的帮助!

    SELECT (SELECT Name FROM NameLookup WHERE NameIndex = bn.NameOne) AS NameOne,
            (SELECT Name FROM NameLookup WHERE NameIndex = bn.NameTwo) AS NameTwo,
            (SELECT Name FROM NameLookup WHERE NameIndex = bn.NameThree) AS NameThree
    FROM BunchaNames bn

1 个答案:

答案 0 :(得分:2)

为什么不使用左连接

select n1.Name as firstName, n2.Name as secondName, n3.Name as thirdName
from BunchaNames as bn
left join NameLookup as n1 
     on bn.NameOne=n1.nameIndex
left join NameLookup as n2  
     on bn.NameTwo=n2.nameIndex
left join NameLookup as n3  
     on bn.NameThree=n3.nameIndex