Get name column instead of ids from two foreign keys

Posted on

Question :

I need to get both group names as a result, although I have no idea how to do this query.

Table 1 (groups)

+---------+--------+
| id      | name   |
+---------+--------+
| 1       | newb   |
| 2       | user   |
| 3       | editor |
| 4       | boss   |
+---------+--------+

Table 2 (inheritance)

gid = group id; pid = parent id

+---------+--------+
| gid     | pid    |
+---------+--------+
| 3       | 1      |
| 3       | 2      |
| 4       | 1      |
| 4       | 2      |
| 4       | 3      |
+---------+--------+

Expected Results

Now I want the names of the groups as a result, not the ids, so I need to get this result:

+---------+--------+
| gname   | pname  |
+---------+--------+
| editor  | newb   |
| editor  | user   |
| boss    | newb   |
| boss    | user   |
| boss    | editor |
+---------+--------+

Thanks!

Answer :

You need to use 2 copies of names table:

SELECT groups_1.name AS gname, groups_2.name AS pname
FROM inheritance
JOIN groups AS groups_1 ON inheritance.gid = groups_1.id
JOIN groups AS groups_2 ON inheritance.pid = groups_2.id

Leave a Reply

Your email address will not be published. Required fields are marked *