简体   繁体   中英

what is the most efficient way to write this sql?

I have an ADUser parent table like this:

ADUser
------
Id => uniqueidentifier
FirstName => varchar(100)
LastName => varchar(100)
CreatedBy => uniqueidentifier
UpdatedBy => uniqueidentifier

And I have a [User] child table used to store an additional PersonalEmail user attribute like this:

User
-------
Id => uniqueidentifier
ADUserId => uniqueidentifier
PersonalEmail => varchar(100)
CreatedBy => uniqueidentifier
UpdatedBy => uniqueidentifier

I can write a query like this to get FirstName, LastName and PersonalEmail of all users:

SELECT 
    adu.FirstName, 
    adu.LastName,
    u.PersonalEmail
FROM 
    ADUser adu
JOIN 
    [User] u ON adu.Id = u.ADUserId

But let's say that I need to add the following columns to the result set to reflect CreatedBy and UpdatedBy columns from the [User] table:

CreatedByName (user.FirstName + " " + user.LastName)
UpdatedByName (user.FirstName + " " + user.LastName)

What would be the most efficient way to update my query to resolve these additional columns?

INNER JOIN back the User table with a different table alias

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM