简体   繁体   English

SQL自连接问题

[英]SQL Self Join issues

I've got 2 tables that I need to get data from...my users table looks like this: 我有2个表需要从中获取数据...我的用户表如下所示:

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. UserID引用回Users表中的UserID,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. 我在如何编写SQL以显示给定用户ID的备用用户方面处于空白。 So if I passed in UserID = 1, it would return: 因此,如果我传递的UserID = 1,它将返回:

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): 我尝试了此操作,但它返回了2行相同的用户数据(在本例中为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. 从您的请求看来,您不需要两次连接到Users表,因为UserAlternates表已经包含原始UserID。

You've got the wrong table alias: 您使用了错误的表别名:

WHERE ua.UserID = @UserID

Note: ua not u. :UA为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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