Grouping SQL results from a Union
I have a table in my database used for users to follow eachother.
The table goes as follows:
UniqueID
FollowerID
FollowedUserID
FollowID is the UserID of the person who is following someone else.
FollowedUserID is the UserID of the person who is being followed by the FollowID User.
I'd like to retrieve a list of connections from this table开发者_如何学编程 based off a single user. My query should return all the other UserIDs that the current user is either following or being followed by with no overlaps.
So say we have a few entries here:
FollowerID FollowedUserID
1 2
1 3
4 1
2 1
This would show that the User 1 is following users 2 and 3, and thus users 2 and 3 are being followed by user 1. On the other side of the spectrum it shows that User 1 is followed by users 2 and 3.
What I'd like to do is find out the connections that user 1 has, so the query should return users: 2, 3, and 4 (user 1 is following users 2 and 3 and is being followed by user 4)
How can I achieve this from a single query?
A connection is considered either being followed or following someone else, so it is possible that some duplicate results can occur (if both users are following eachother). I'd like to be able to group these results so that the result is distinct.
I've tried a UNION query similar to:
SELECT FollowerID, FollowedUserID From Follows WHERE FollowerID = 1
UNION
SELECT FollowerID, FollowedUserID FROM Follows WHERE FollowedUserID = 1
Theoretically I'd like to Group FollowerID and FollowedUserID together to keep them distinct.
I'm not interested in retrieving a non-distinct result and then creating a dataset of unique results php side -- the query should return distinct values only.
You were close, but you have to reverse the order of the columns in one of the branches of the UNION:
SELECT FollowerID AS reference_user, FollowedUserID AS connection
FROM Follows
WHERE FollowerID = 1
UNION
SELECT FollowedUserID AS reference_user, FollowerID AS connection
FROM Follows
WHERE FollowedUserID = 1
GROUP BY reference_user;
Note that if you drop the WHERE clauses, you get all connections for everyone.
I think you'd need to revise your query:
edit: removed the un-needed select distinct
SELECT FollowedUserID as ID From Follows WHERE FollowerID = 1
UNION
SELECT FollowerID as ID FROM Follows WHERE FollowedUserID = 1
But that doesn't quite answer the question of direction.
SELECT FollowedUserID as ID, "follow" as direction
From Follows
WHERE FollowerID = 1
UNION
SELECT FollowerID as ID, "followed" as direction
FROM Follows
WHERE FollowedUserID = 1
Now you know the direction of the connection as well.
精彩评论