Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 280
Atticus Avatar asked Mar 02 '26 05:03

Atticus


1 Answers

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.

like image 70
Jonathan Leffler Avatar answered Mar 04 '26 18:03

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!