简体   繁体   中英

SQL Self Join issues

I've got 2 tables that I need to get data from...my users table looks like this:

Users Table
-------------
UserID
FirstName
LastName
WebLogin
WebPassword
Active

UserAlternates Table
---------------------
UserAlternateID
UserID
AlternateUserID

Users Table Data
------------------
1, John, Brown, jbrown, jbrown, true
2, Mark, Smith, msmith, msmith, true
3, Tim, Stone, tstone, tstone, true

UsersAlternate Table Data
--------------------------
1, 1, 2
2, 1, 3
3, 2, 1
4, 3, 2
5, 3, 1

The UserID refers back to the UserID in the Users table and so does the AlternateUserID. This is a case where our program can have users that are "alternates" to other users. So in the above example, if John Brown would have Mark & Tim as Alternates, and Mark would have John as an alternate while Time would have Mark and John as alternates. I'm drawing a blank on how to write the SQL to show the alternate users for a given userid. So if I passed in UserID = 1, it would return:

2, Mark, Smith
3, Tim, Stone

I tried this but it returns 2 rows of the same user data (in this case, 2 John Brown's):

CREATE      PROCEDURE [dbo].[GetUserAlternates]
@UserID int

 AS
SELECT u.FirstName, u.LastName, ua.AlternateUserID
FROM Users u
INNER JOIN UserAlternates ua ON u.UserID = ua.AlternateUserID
WHERE u.UserID = @UserID

Any ideas?

CREATE PROCEDURE dbo.GetUserAlternates
    @UserID INT
AS
BEGIN
    SET NOCOUNT ON;

    SELECT u.FirstName, u.LastName, u.UserID
      FROM dbo.Users AS u
      INNER JOIN dbo.UserAlternates AS au
      ON u.UserID = ua.AlternateUserID
    WHERE ua.UserID = @UserID; -- key difference here!
END
GO

How about something like

SELECT  u.*
FROM    UserAlternates ua   INNER JOIN
        Users u ON  ua.AlternateUserID = u.UserID
WHERE   ua.UserID = @UserID 

It does not seem from your request that you need to join to the Users table twice, as the UserAlternates table already contains the original UserID.

You've got the wrong table alias:

WHERE ua.UserID = @UserID

Note: ua not u.

SELECT ua.AlternateUserID, U2.FirstName, U2.Lastname
FROM Users u
  INNER JOIN UserAlternates ua ON u.UserID = ua.UserID
  INNER JOIN Users U2 on U2.UserID = UA.AlternateUserID
WHERE u.UserID = @UserID

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