0

I have a table swipe that I need to iterate through to fill an array that I can use to display a matches list to the user. The structure is the following (a valid match between two users):

enter image description here

Here is my raw logic to iterate through the table and get match objects that I will push into an array:

user = current_user_id;

for (swipes in swipe)
{
  if (id_user === user)
  {
    to_match === id_user_matched;
    for (swipes in swipe)
    {
        if (id_user === to_match && id_user_matched === user)
        {
            matches_list[].push({“id_match”: id_match, “id_user_matched”: to_match});
        }
    }
  }
}

How can I do this in my backend with either an sql query or Node code?

Thank you!

2
  • If I have understood well, you can create the mysql query in order to retrieve just to rows concerning to id_user you want. After that you can populate the array with the query result. Commented Jun 25, 2019 at 13:38
  • @Wolfetto do you think it's possible in a single query? Commented Jun 25, 2019 at 13:41

1 Answer 1

1

I know nothing about node, but the SQL you want to run will look something like this:

select s2.id_match, s1.id_user_matched
from swipe s1
inner join swipe s2 ON s2.id_user = s1.id_user_matched and s2.id_user_matched = @user
where s1.id_user = @user
Sign up to request clarification or add additional context in comments.

5 Comments

It work by joining the table to itself. This replaces the loops in the sample code from the question... run the query, and the results go directly into the matches_list array. But again, I've never used node, so figuring out how to run the query is up to you.
Amazing! What do s1 and s2 mean?
Table aliases, so you can distinguish the two instances of the table from each other.
Thank you Joel! It works like a charm, SQL seems to be very powerful, is my query realistic in a production environment?
Yes, this is realistic

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.