mysql连表查子级
时间: 2023-08-19 21:11:50 浏览: 97
sql查询子级和父级
在MySQL中,可以使用连接操作来查询子级。以下是一个示例查询语句:
SELECT T2.id, T2.name
FROM (
SELECT @r AS _id, (SELECT @r := parent_id FROM material_category WHERE id = _id) AS parent_id, @l := @l + 1 AS lvl
FROM (SELECT @r := 807984712867205120, @l := 0) vars, material_category h
WHERE @r <> 0
) T1
JOIN material_category T2 ON T1._id = T2.id
ORDER BY T1.lvl DESC;
这个查询语句使用了连接操作来查询子级。首先,通过子查询将父级ID和子级ID放入一个临时表中。然后,使用连接操作将临时表与原始表进行连接,以获取子级的详细信息。最后,按照层级进行降序排序,以便正确显示父子关系。
请注意,你需要将上述查询中的"material_category"替换为你实际使用的表名,并将"807984712867205120"替换为你要查询子级的父级ID。
#### 引用[.reference_title]
- *1* [Mysql递归查询子级(父子级结构)&从子级ID查询所有父级(及扩展知识)](https://blog.csdn.net/qq_16992475/article/details/121783805)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [mysql根据子级查询父级, 根据父级查询子级(递归查询)](https://blog.csdn.net/boveysmith/article/details/129417613)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文