我有一个示例代码:
products(id, parent_id, name)
1 | 0 | product1
2 | 0 | product2
3 | 1 | product1_1
4 | 1 | product1_2
5 | 2 | product2_1
6 | 2 | product2_2
并查询:
SELECT prod.id, prod.name
FROM `products` AS prod
INNER JOIN `products` AS prod_parent ON prod_parent.product_id = prod.parent_id
但结果是:
3 | product1_1
4 | product1_2
5 | product2_1
6 | product2_2
如何获得父亲的父亲
1 | product1
2 | product2
答案 0 :(得分:1)
在您的SELECT
列表中明确指定您想要的表格。这将为您提供所有四列,但您可以将其修剪为仅需要的列。
SELECT
prod.id AS prod_id,
prod.name AS prod_name,
prod.parent_id AS parent_id,
prod_parent.name AS parent_name
FROM `products` AS prod
LEFT JOIN `products` AS prod_parent ON prod_parent.product_id = prod.parent_id