gogoWebsite

MySQL parent-child structure query in the same table

Updated to 17 days ago

For example, in the yjy_content_type table, parent_id is the parent id, sort is the sort field, and both the parent and children need to be sorted according to their own level.

Idea: When querying, first add the parent sort g_max_sort to the child (this field is mainly used for parent sorting), and then use another field sortg to show whether it is the same group (if there is parent_id, use the parent_id value, otherwise use your own id value).

SELECT
	a.`id`,
	a.`parent_id`,
	a.`sort`,
	(CASE  WHEN a.parent_id!=0 THEN  ELSE  END ) as g_max_sort,
	(CASE a.parent_id WHEN 0 THEN  ELSE a.parent_id END ) as sortg,
	 AS status_text,
	a.`content`,
	a.`title`,  
	a.`status`,
	a.create_time AS create_time_text 
FROM
	`yjy_content_type` `a`  LEFT JOIN  yjy_content_type b ON a.parent_id=
	
	ORDER BY g_max_sort desc ,sortg,parent_id,sort desc

The table is connected because the parent also needs to be sorted, otherwise you can do not need to add g_max_sort and table connection operations.