Skip to content
Advertisement

Foreign Key Refers the Primary Key Columns of Same Table

I have two tables like this:

Table 1 – CivilOffices

Table 2 – Offices

I want to query all the offices with their respective parent office name. But when I tried to query this, the query returns the parent office id instead of parent office name.

Here is the query I used.

Here is the result

Instead, I want result something like this

Advertisement

Answer

I would approach this as follows:

We do a self-join on the CivilOffices table to match each record with a potential parent. Then, we use two separate joins to Offices to bring in the office name as well as possibly the parent office name, should the latter exist.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement