我有一个示例数据:
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
但结果为null,如何修复此查询
答案 0 :(得分:0)
你必须自我加入:
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