mysql从另一个tabel获取id和父id的名称?

hof1towb  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(406)

我有两张table。
表1:[身份证,父母身份证,姓名身份证]
表2:[姓名\u id,姓名]
我想为每个id显示连接到表2的name\u id的名称和父项的名称(parent\u id raprevent the id of the same table1)
例子:

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

现在,我在这里,带着我的名字

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

我怎样才能得到父母的名字?谢谢

zxlwwiss

zxlwwiss1#

可以执行多个联接:

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
izj3ouym

izj3ouym2#

通过使用别名,您可以引用同一个表两次,连接每个id字段。

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
dfuffjeb

dfuffjeb3#

可以使用多个联接并为它们指定别名。类似的东西(未经测试)

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

相关问题