我有一个具有以下字段的MySQL表:
id name parent 1 Fruit 0 2 Meat 0 3 Orange 1 4 Beef 2
其中父字段表示上层ID。例如,水果id是1,橙色是水果之一,因此父对象是1。
但是我想做一个有效的MySQL查询来获取所有记录,格式为parent-> children-> parent-> children格式。我怎样才能做到这一点?
查询的结果记录应类似于:
id name parent 1 Fruit 0 3 Orange 1 2 Meat 0 4 Beef 2
您需要mysql不支持的递归联接。您唯一可以做的就是确定最大深度(由于p-> c,所以我将其设置为1),并以此确定所需的联接数:
最大深度=自连接数 :
SELECT p.id as parent_id, p.name as parent_id, c1.id as child_id, c1.name as child_name FROM my_table p LEFT JOIN my_table c1 ON c1.parent = p.id WHERE p.parent=0
例如,如果最大深度为3,则需要3个自联接:
SELECT p.id as parent_id, p.name as parent_id, c1.id as child_id_1, c1.name as child_name_1, c2.id as child_id_2, c2.name as child_name_2, c3.id as child_id_3, c3.name as child_name_3 FROM my_table p LEFT JOIN my_table c1 ON c1.parent = p.id LEFT JOIN my_table c2 ON c2.parent = c1.id LEFT JOIN my_table c3 ON c3.parent = c2.id WHERE p.parent=0