無限層級mysql資料表結構

2021-08-30 02:15:29 字數 1583 閱讀 2171

# 無限層級mysql資料表結構

# 建立表

-- auto-generated definition

create table target_resource

( id int not null

primary key,

resource_id int null,

resource_team_id int null

);# 建立關係表

-- auto-generated definition

create table agent_tree_path

( parents_team_id int not null,

son_team_id int not null,

path_length int default '0' null,

primary key (parents_team_id, son_team_id),

constraint agent_tree_path_ibfk_1

foreign key (son_team_id) references target_resource (id)

);create index son_team_id

on agent_tree_path (son_team_id);

# 插入到關係表

insert into agent_tree_path (parents_team_id, son_team_id, path_length)

select t.parents_team_id, 7, t.path_length + 1

from agent_tree_path as t

where t.son_team_id = 6

union all

select 7, 7, 0;

# 刪除子節點

delete

from agent_tree_path

where son_team_id = 7;

# 要刪除一顆完整的子樹,parents_team_id 和他的後代

delete

from agent_tree_path

where son_team_id in (select son_team_id from agent_tree_path where parents_team_id = 4);

# 查詢子節點的所有父節點

select t.*

from target_resource as t

inner join agent_tree_path a on t.id = a.parents_team_id

where a.son_team_id = 6;

# 查詢父節點所有的子節點

select t.*

from target_resource as t

inner join agent_tree_path a on t.id = a.son_team_id

where a.parents_team_id = 6

MySQL 無限層級資料表設計

需求 使用者a介紹b入會,b成為a的下線,b再發展c d等下線,c d也允許發展下線,不限制層級,但是每個人只允許有乙個上線 類似 傳銷 典型的樹結構 問題 快速查詢某人的所有上線 快速查詢某人的所有下線 快速為某人增加乙個下線 方案有以下四種,各自的定義和利弊請看 前輩的文件 一 鄰接表 依賴父節...

mysql 匯出表資料表結構

在命令列下mysql的資料匯出有個很好用命令mysqldump,它的引數有一大把,可以這樣檢視 mysqldump 最常用的 mysqldump uroot pmysql databasefoo table1 table2 foo.sql 這樣就可以將資料庫databasefoo的表table1,t...

mysql更新表結構 mysql更新資料表結構命令

mysql中alter命令的用法,用於編輯表結構 修改表名alter table test rename test1 修改字段型別alter table employee change depno depno int 5 not null 加索引alter table 表名 add index 索引...