Skip to content
Advertisement

MySql query to check list of ids if they are friends with me?

So I have a list of ids(userId’s) that was found using a sql command that I want to check with my friends table to see if they are indeed friends with myself, a userid I will provide with, and have a column that will represent if they are and also group them if they are my friend and not my friend.

Example:

sample friends table data

I tried creating a subquery that would first get the list of ids I want, and then tried to compare it with my friends table but couldn’t quite put it together because the friends table is not bidirectional, meaning each row represents a relationship between 2 people with a status friends or pending

Advertisement

Answer

Use a CASE expression to get the friend of a person (i.e. pick either the userid or the friendid from the friends table).

As of MySQL 8 you can use a WITH clause to get this readable:

The same without WITH:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement