Search code examples
mysqlsqlsubquery

Replacing associated values in SQL?


I have a SQL Db that I am trying to query, consisting of three tables - Members, Bookings, and Facilities (country club stuff)

There is a memid column associated with each member, for which I have a first and a last name, and also who recommended them, recommendedby. Recommendedby is utilizing this memid, and I need to replace the number representing memid in recommendedby with The actual name of the person who recommended them. Any idea how I'd do this?

Here's a screenshot of the database:

Screenshot of Database

As you can see, the first/surname columns are the names of the people, and each one of them is represented by a memid, and then that same memid is used to identify who recommended them, and again I need to replace those numbers in recommendedby with the actual name of the recommending member.


Solution

  • That's a self-join:

    select m.*, 
        r.surname   recommendedby_surname, 
        r.firstname recommendedby_firstname
    from members m
    inner join members r on r.memid = r.recommendedby