mrqwerty91
mrqwerty91

Reputation: 170

mysql get name of id and parent id from another tabel?

i have 2 table.

table1: [id, parent_id, name_id]

table2: [name_id, name]

i would like to show for every id the name connected to the name_id of table2 and the name of the parent (parent_id rapresent the id of the same table1)

Example:

table1:
id     parent_id   name_id
1          0         100
2          1         101

table1:
name_id    name
 100       food
 101       fruit

output:
id     parent_id   name_id   name_id   parent_name_id
1          0         100      food           0
2          1         101      fruit        food

For now, i'm here, with the name of the name_id

SELECT table1.id, table1.parent_id , table1.name_id , table2.name_it
FROM table1 join table2 on table1.name_id = table2.name_id 
output:
id     parent_id   name_id   name_id   
1          0         100      food     
2          1         101      fruit   

How can i get the parent_name_id? thanks

Upvotes: 0

Views: 185

Answers (3)

teldri
teldri

Reputation: 326

You can use multiple joins and give them alias names to work with. Something like that (untested)

SELECT table1.id, table1.parent_id , table1.name_id , table2.name_it, t2_parent.name as parent_name
FROM table1 
join table2 on table1.name_id = table2.name_id 
join table1 t1_parent on t1_parent.id = table1.parent_id
join table2 t2_parent on t1_parent.name_id = table2.name_id 

Upvotes: 0

Anna
Anna

Reputation: 1

By using aliases, you can reference the same table twice, joining each id field.

SELECT a.id, 
    a.name_id, 
    b.name as name,
    a.parent_id, 
    c.name as parent,
FROM table1 as a
join table2 as b on a.name_id = b.name_id 
join table2 as c on a.parent_id = c.name_id 

Upvotes: 0

GMB
GMB

Reputation: 222432

You can do multiple joins:

select t1.*, t2.name, t20.name parent_name
from table1 t1
inner join table2 t2 on t2.name_id = t1.name_id
left  join table1 t10 on t10.id = t1.parent_id
left  join table2 t20 on t20.name_id = t10.name_id

Upvotes: 1

Related Questions