I'm having a problem with a N:N table in my database. I used the following stackoverflow question to help me in this matter:
How to make SQL many-to-many same-type relationship table
I have a concept of users and these users can maintain a friends list. I created the following 2 tables:
CREATE TABLE [dbo].[Users] (
[UserId] UNIQUEIDENTIFIER NOT NULL,
[UserName] NVARCHAR (50) NOT NULL,
[Password] NVARCHAR (88) NOT NULL,
[E-Mail] NVARCHAR (100) NOT NULL,
[First Name] NVARCHAR (50) NOT NULL,
[Last Name] NVARCHAR (50) NOT NULL,
[Description] NVARCHAR (2000) NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC)
);
GO
CREATE TABLE [dbo].[Friends]
(
[Id] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY,
[UserId] UNIQUEIDENTIFIER NOT NULL,
[FriendId] UNIQUEIDENTIFIER NOT NULL
)
GO
I then ran the following alteration query:
ALTER TABLE Friends ADD FOREIGN KEY (userid) REFERENCES Users (userid);
ALTER TABLE Friends ADD FOREIGN KEY (friendid) REFERENCES Users (userid);
I ran the following INSERT query:
INSERT INTO Friends
VALUES (NEWID(), 'AC30D0BB-3462-4D87-A132-62BE6EBA8E82', '6CD2EC21-C32B-4EC3-B221-E36E2A887EA0');
and lastly I ran this query to attempt to retrieve the info:
SELECT *
FROM Users u
INNER JOIN Friends f ON u.userid = f.userid
INNER JOIN Friends f ON u.userid = f.friendid
WHERE
(f.userid = 'AC30D0BB-3462-4D87-A132-62BE6EBA8E82' OR f.friendid = 'AC30D0BB-3462-4D87-A132-62BE6EBA8E82')
AND u.userid != 'AC30D0BB-3462-4D87-A132-62BE6EBA8E82';
This presents the following error:
Msg 1011, Level 16, State 1, Line 4
The correlation name 'f' is specified multiple times in a FROM clause.
I understand why I'm getting this error but any changes I make result in no records being retrieved from the DB, can anyone explain what I've done wrong?
Thanks
EDIT 1:
As per first comment:
SELECT *
FROM Users u
INNER JOIN Friends f1 ON u.userid = f1.userid
INNER JOIN Friends f2 ON u.userid = f2.friendid
WHERE
(f1.userid = 'AC30D0BB-3462-4D87-A132-62BE6EBA8E82' OR f2.friendid = 'AC30D0BB-3462-4D87-A132-62BE6EBA8E82')
AND u.userid != 'AC30D0BB-3462-4D87-A132-62BE6EBA8E82';
Retrieves nothing.
EDIT 2: Basically I am trying to retrieve all of a given user's friends. Is it possible that my tables are set up incorrectly or my data is invalid? I have 3 users in my Users table, one with UserId of AC30D0BB-3462-4D87-A132-62BE6EBA8E82.