简体   繁体   中英

How to merge two tables where one is parent of the other?

I am trying to merge two tables together and maintain the fact that one is the child of the other table. i want to show that it has a parent while still maintaining the parent with its unique values.

here's what i have in relations: subdomain.domain_id is related to (you guessed it) domain.id

my table examples

domain:

id | name | description | validator | need | need_amount
---|------|-------------|-----------|------|-------------
5  | prog | this iss..  | 6         | low  | 5

subdomain

id | name | description | validator | domain_id | need | need_amount
---|------|-------------|-----------|-----------|------|------------
5  | java | java is...  | 10        | 5         | high | 10
6  | c++  | c++...      | 9         | 5         | high | 10

i want to be able to see

id | domain_name | subdomain_name | description | validator | need | need_amount
---|-------------|----------------|-------------|-----------|------|-------------
5  | prog        | null           | this iss..  | 6         | low  | 5
5  | prog        | java           | this is...  | 10        | high | 10
6  | prog        | c++            | this is..   | 9         | high | 10

OR like this, (ideally the one above)

id | name         | description | validator | need | need_amount
---|--------------|-------------|-----------|------|------------
5  | prog         | this iss..  | 6         | low  | 5
5  | prog - java  | java is...  | 10        | high | 10
6  | prog - c++   | c++...      | 9         | high | 10

Any ideas??? is it possible? Thanks!

Thanks to @Pradeep

SELECT id,
       name AS domain_name,
       NULL AS subdomain_name,
       description,
       validator,
       need,
       need_amount
FROM   domain 
UNION ALL
SELECT a.id,
       b.name AS domain_name,
       a.name            AS subdomain_name,
       a.description,
       a.validator,
       a.need,
       a.need_amount
FROM   subdomain a join domain b on a.domain_id=b.id 

try this.

SELECT id,
       name AS domain_name,
       NULL AS subdomain_name,
       description,
       validator,
       need,
       need_amount
FROM   parent 
UNION ALL
SELECT a.id,
       b.domain_name AS domain_name,
       a.name            AS subdomain_name,
       a.description,
       a.validator,
       a.need,
       a.need_amount
FROM   child a join parent b on a.domain_id=b.domain_id 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM