
uid 用戶ID, mycode 我的邀請碼, pcode 我的上級邀請碼, rflag 已認證。
表結構如圖所示,請問如何通過SQL陳述句或者自定義函式查詢出子節點及其子節點的子節點。
例如 uid為1的用戶,邀請了2和3,2和3繼續邀請。
那么我統計u1時,查詢結果為8(排除自己)。如何實作?
uj5u.com熱心網友回復:
https://dev.mysql.com/doc/refman/8.0/en/with.htmluj5u.com熱心網友回復:
這個是自連接首先建臨時表--取幾級關聯幾次
create table table_2 as
select
t.uid,
count(distinct t1.uid) u_cnt_1, --一級
count(distinct t2.uid) u_cnt_2 --二級
from
(select uid,mycode,p_code from table) t
left join
(select uid,mycode,p_code from table) t1
on t.mycode=t1.p_code
left join
(select uid,mycode,p_code from table) t2
on t1.mycode=t2.p_code
;
然后將所需要的到幾級的人數加在一起
select
uid,
u_cnt_1+u_cnt_2
from table_2;
uj5u.com熱心網友回復:
樓主你好,可以用遞回的方法來實作,代碼如下
CREATE DEFINER=`root`@`%` PROCEDURE `Proc_GetMySub`(IN `InUid` int)
label_pro:BEGIN
DECLARE userCode int DEFAULT 0;
SELECT mycode into userCode FROM tb_xx;
-- 建一個臨時表
DROP TABLE IF EXISTS tbTem_userId;
create table tbTem_userId(uid INT);
-- 我的第一下級
INSERT INTO tbTem_userId SELECT uid FROM tb_xx WHERE pcode = userCode;
-- 我的第二下級
INSERT INTO tbTem_userId SELECT uid FROM tb_xx WHERE pcode IN (SELECT uid FROM tb_xx WHERE pcode = userCode);
-- 查詢出所有的下級
SELECT uid FROM tbTem_userId;
END
如果要查詢多個下級一次類推,不過不建議下級超過5級,即使用其他的遞回查詢也是效率極低,如果非要用多級的話建議樓主根據應用場景重新設計表以便達到較好的查詢效率
uj5u.com熱心網友回復:
要實作你所說的功能,用你現在的資料結構是可以實作,但效率極度低下。。建議更改資料結構。。
參照下資料的幾種樹形結構,都可以輕松實作你的需求,比如物化路徑,左右值樹
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/55756.html
標籤:MySQL
上一篇:資料庫連接報錯1130,且本機也連接不上資料庫,求解決方法!!!急急急!!
下一篇:mysql 查詢
