Search code examples
mysqlsqlselectqsqlquery

A query which returns a name and his/her friends, based on relId


I'm new in sql. I got stuck into this problem, and I can't figure it out how can I solve this.

I've got 2 tables.

  1. person: personId,name.
  2. personRel: id,personId,relId(personId).

The problem is: How can I return with one query the person's name and the other's name, whom they knew.


Solution

  • You would use two joins:

    select pr.*, p.name, ppr.name as rel_name
    from personRel pr left join
         person p
         on p.personid = pr.personid left join
         person ppr
         on ppr.personid = pr.relid;