premise
mainly uses the find_in_set
function, and the :=
operator;
If you don’t understand, you can learn about this Here is a brief explanation of the functions of these two things:
find_in_set is to determine whether a string spliced with commas contains a certain string, such as : means setting the value, and then It is the same in addition, modification and query. For example, select @num:=@num+1, which means setting the num value to increase by 1. :=find_in_set('a','a,b,c')
, returns the position of a in the following set, here it is 1;
Instance table:
order_num value storage rule:
Add 1 to every 9, 91 (not equal to greater than 10, otherwise there will be a problem), a>这是另个涉及排序的问题,这里不用关注
.
Query all subsets
SELECT
order_num,
id,
type_name ,
ischild
FROM
(
SELECT
t1.order_num,
t1.id,
t1.type_name,
IF
( find_in_set( parent_id, @pids ) > 0, @pids := concat( @pids, ',', id ), '0' ) AS ischild
FROM
( SELECT order_num, id, type_name, parent_id FROM hw_baseinfo_project_type t WHERE del_flag = 0 ORDER BY order_num ) t1,
( SELECT @pids := 'f6d225fdff64e96123aaf251e1b52bc1' ) t2
) t3
WHERE
ischild != '0' or id = 'f6d225fdff64e96123aaf251e1b52bc1' -- (带本级)
-- ischild != '0'(不带本级)
Query all parents
SELECT
order_num,
id,
type_name ,
isParent
FROM
(
SELECT
t1.order_num,
t1.id,
t1.type_name,
IF
( find_in_set( id, @ids ) > 0, @ids := concat( @ids, ',', parent_id ), '0' ) AS isParent
FROM
( SELECT order_num, id, type_name, parent_id FROM hw_baseinfo_project_type t WHERE del_flag = 0 ORDER BY order_num desc) t1,
( SELECT @ids := 'f555fe921b95ad59a35394c2d07173b7' ) t2
) t3
WHERE
isParent != '0'
Try it yourself.
当然,并不是只能传递一个值,多个值也是可以的啊
This will query the superiors of multiple subsets or the collection of subsets of multiple superiors.