MYSQL 查找全部的父級或子級(多級)

語句的做用

若是用php程序查詢的話,要用遞歸屢次查詢數據庫,很慢,也增長了服務器的壓力,後來發現用一句sql就能直接返回全部的父級或子級php

用戶表sql

t_id  |  parent_id  
1     |  0  
2     |  1
3     |  0 
4     |  2
5     |  4

查找父級例子

sql語句 查找全部父級(包含自己)數據庫

SELECT T2.t_id
            FROM (
                  SELECT
                    @r AS _id,
                    (SELECT @r := parent_id FROM t_user WHERE t_id = _id) AS parent_id,
                    @l := @l + 1 AS lvl FROM (SELECT @r := 5, @l := 0) vars,
                    t_user h WHERE @r <> 0 AND parent_id > 0
                 ) T1 JOIN t_user T2 ON T1._id = T2.t_id ORDER BY T1.lvl DESC

篩選結果服務器

|t_id|
|1   | 
|2   | 
|4   | 
|5   |

查找子級例子

sql語句 查找全部子級(不包含自己).net

SELECT t_id FROM
  (
    SELECT * FROM t_user where parent_id > 0 ORDER BY parent_id, t_id DESC
  ) realname_sorted,
  (SELECT @pv :=1) initialisation
  WHERE (FIND_IN_SET(parent_id,@pv)>0 And @pv := concat(@pv, ',', t_id))

篩選結果code

|t_id|
|2   | 
|4   | 
|5   |

查找子級是同事寫的,查找父級是本身寫的,記下來方便之後用blog

根據一級節點查找對應的二級子節點數量遞歸

SELECT t_id, ( SELECT count(a.parent_id) FROM t_user a WHERE a.parent_id = b.t_id) count FROM t_user b WHERE b.parent_id = 0

篩選結果it

|t_id|count
|1   | 1
|3   | 0

參考文章

http://blog.csdn.net/itchiang/article/details/9270245
相關文章
相關標籤/搜索