简体   繁体   English

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

[英]mysql get name of id and parent id from another tabel?

i have 2 table.我有 2 张桌子。

table1: [id, parent_id, name_id]表 1:[id,parent_id,name_id]

table2: [name_id, name]表 2:[name_id,名称]

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)我想为每个 id 显示连接到 table2 的 name_id 的名称和父级的名称(parent_id 表示同一个 table1 的 id)

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现在,我在这里,名称为 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?我怎样才能得到 parent_name_id? thanks谢谢

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

By using aliases, you can reference the same table twice, joining each id field.通过使用别名,您可以引用同一个表两次,连接每个 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 

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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