Question: I have 3 tables in my database, in which `team1` and `team2` ids in `Matches` Table are equal to `team_id` in `TeamNames` Table.

also `group` in `Matches` Table is equal to `group_id` in `GroupNames` Table

*`Matches` Table*

```
 -----------------------------------
| team1 | team2 |  group  |  count  |
|   3   |   5   |   1     |    1    |
|   1   |   2   |   3     |    0    |
 -----------------------------------

```

*`GroupNames` Table*

```
 -----------------------
| group_id |    name    |
|     1    |   Finals   |
|     3    | Semi-Final |
 -----------------------

```

*`TeamName` Table*

```
 -----------------------
|  team_id |    name    |
|     5    |   Flowers  |
|     2    |   Rainbow  |
 -----------------------

```

What I need to get is:

`SELECT team1 , team1_name , team2 , team2_name , group , group_name WHERE count=1`

I tried joining tables, but as each of the team1 and team2 should be related to unique id in TeamName Table I failed, getting group name was easy, but I failed getting all the above in single query

Questions:

1. Is this possible in single query?
2. Can this be done using CodeIgniter's "[Active Record Class](https://ellislab.com/codeigniter/user-guide/database/active_record.html)"?

Answer: 
It is not exactly clear what you are asking.

However it would appear you are talking about a self-referencing relationship rather than Inheritance so you can then map as below. The default fetch strategy should be same as for any other `@OneToMany` i.e. LAZY.

```
@Entity
public class Category{

    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Category parent;

    @OneToMany(mappedBy = "parent")
    private Set<Category> subCategories;
}

```
I believe you want to ask about inheritance of entities. I recommend using JPA inheritance strategies. There are 3 available. 

1. [Single Table](http://www.thejavageek.com/2014/05/14/jpa-single-table-inheritance-example/): Uses only one database table. columns need to be nullable and hence wastes database space
2. [Joined Strategy](http://www.thejavageek.com/2014/05/17/jpa-joined-inheritance-example/): Uses multiple table which can be joined for insertion and retrieval of entity data. Saves database space but performance becomes an issue when inheritance hierarchy becomes wide and deep
3. [Table per concrete class](http://www.thejavageek.com/2014/05/17/jpa-table-per-concrete-class-example/): Uses separate database tables which are not joined.

Different strategies have different advantages and disadvantages. You can choose according to your need.