我有一个像这样的ADUser父表:
ADUser
------
Id => uniqueidentifier
FirstName => varchar(100)
LastName => varchar(100)
CreatedBy => uniqueidentifier
UpdatedBy => uniqueidentifier
我有一个[User]子表用于存储另外的PersonalEmail用户属性,如下所示:
User
-------
Id => uniqueidentifier
ADUserId => uniqueidentifier
PersonalEmail => varchar(100)
CreatedBy => uniqueidentifier
UpdatedBy => uniqueidentifier
我可以编写这样的查询来获取所有用户的FirstName,LastName和PersonalEmail:
SELECT
adu.FirstName,
adu.LastName,
u.PersonalEmail
FROM
ADUser adu
JOIN
[User] u ON adu.Id = u.ADUserId
但是,我们要说我需要将以下列添加到结果集中,以反映CreatedBy
表中的UpdatedBy
和[User]
列:
CreatedByName (user.FirstName + " " + user.LastName)
UpdatedByName (user.FirstName + " " + user.LastName)
更新查询以解决这些额外列的最有效方法是什么?
答案 0 :(得分:2)
INNER JOIN使用不同的表别名
返回User表SELECT
adu.FirstName,
adu.LastName,
u.PersonalEmail,
CreatedByName = c.FirstName + ' ' + c.LastName,
UpdateByName = p.FirstName + ' ' + p.LastName
FROM
ADUser adu
INNER JOIN
[User] u ON adu.Id = u.ADUserId
INNER JOIN
[ADUser] c ON u.CreatedBy = c.Id
INNER JOIN
[ADUser] p ON u.UpdatedBy = p.Id