I have two tables. Table 1. (tbl_1)
| ID | Name |
| -- | -------------|
| 1 | Company1 |
| -- | -------------|
| 2 | Company2 |
| -- | -------------|
| 3 | Company2 |
Table 2. (tbl_2)
| ID | Company_group |
| -- | ------------- |
| 1 | Company2 |
| -- | ------------- |
| 2 | Company2 |
| -- | ------------- |
| 3 | Company2 |
I now that Company_2 is parent company an i want to get next result.
| ID | Name | RootName | RootId |
| -- | -------------| --------- | ------ |
| 1 | Company1 | Company2 | 2 |
| -- | -------------| ----------|--------|
| 3 | Company3 | Company2 | 2 |
I don't know parentId. But i can select all parent companies with follow query:
SELECT DISTINCT id parentId,
name parent_name FROM tbl_1 WHERE name in (
SELECT DISTINCT
Company_group
FROM tbl_2)
How can i build tree for this hierarchy? I can not think, please help.
It is a strange architecture for this case but architect of database is not me.
Also i wrote query but it works not correct. It returns more records.
SELECT ac.id_c parentId, acc.id, ac.Company_group parent_name
FROM tbl_2 ac
JOIN tbl_2 acc
ON ac.Company_group = acc.Company_group
AND ac.id in (
SELECT DISTINCT id parentId
FROM tbl_1 WHERE name in (
SELECT DISTINCT
id parentId
FROM tbl_2)
)
WHERE ac.Company_group iS NOT NULL AND acc.id IS NOT NULL
and ac.id <> acc.id
ORDER BY ac.Company_group