我有一个样本数据:
table(id, parent_id, name)
1| 0| Apple
2| 1| Iphone
3| 1| Ipad
4| 1| Macbook
和mysql:
SELECT *
FROM `table` AS brand
WHERE brand.parent_id = brand.id
但结果为空,如何修复此查询
你必须做一个自我加入:
SELECT
a.*,
b.name AS parent_name
FROM
tbl a
LEFT JOIN
tbl b ON a.parent_id = b.id
结果集将类似于:
id | parent_id | name | parent_name
--------------------------------------------------
1 | 0 | Apple | NULL
2 | 1 | Iphone | Apple
3 | 1 | Ipad | Apple
4 | 1 | Macbook | Apple