I am trying to create a function in MySQL for my 'friendships' table where I have 4 columns:
friendship_id, status, user1_id and user2_id (last two are also foreign keys which point to another table 'users').
Function should receive one parameter which is users id and return how many friends that user has.
I created a function like this:
CREATE FUNCTION num_of_friends(id int)
RETURNS int(11)
BEGIN
SET @friends_count = (SELECT COUNT(user2_id) FROM friendships WHERE user1_id = id);
RETURN @friends_count;
END
So this function returns number of friends for that specific user, if his id is in column user1_id.
But there are some users whose id is only in the column user2_id.
How could I check if the user's id which we passed as parameter exists in either of the columns and count friendships based on that?