作者cutekid (可爱小孩子)
看板Database
标题Re: [SQL ] 递回查询
时间Tue Mar 27 17:24:37 2018
###########
# test data
create table tmp (
UID int,
marID int
);
insert into tmp select 1, null;
insert into tmp select 2, 1;
insert into tmp select 3, 1;
insert into tmp select 4, 2;
insert into tmp select 5, 7;
insert into tmp select 6, 4;
insert into tmp select 7, null;
################
# Google 关键字:
#
# How to create a MySQL hierarchical recursive query
select UID,marID
from
(
select * from tmp
order by marID
) t1,
(
select @pv := 1
) t2
where find_in_set(marID, @pv)
and length(@pv := concat(@pv, ',', UID))
※ 引述《bill0205 (ZzZz)》之铭言:
: (针对 SQL 语言的问题,用这个标题。请用 Ctrl+Y 砍掉这行)
: 资料库名称: MySQL
: 资料库版本: 5.7
: 内容/问题描述:
: 我有一张table(users) 栏位分别为 UID (PK) , marID(FK,users.UID)
: 我想做递回查询
: 假设有资料为
: UID marID
: 1 NULL
: 2 1
: 3 1
: 4 2
: 5 7
: 6 4
: 7 NULL
: 我有找到相关方法
: with tmpTB ( ... union all ... ) select * from tmpTB;...
: 但是还是失败
: 我想做的是能否利用一个UID 就能找到所有部属
: ex UID = 1
: 则会查到
: UID marID
: 2 1
: 3 1
: 4 2
: 6 4
: 不知道有没有类似方法呢 感谢各位
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 61.221.80.36
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Database/M.1522142679.A.898.html
1F:推 bill0205: 感谢 刚刚我测试了一下 似乎理解了里面的意义 03/28 10:46
2F:→ bill0205: 但刚刚发现一个问题 假设是先insert 4 , 2 再 insert 03/28 11:11
3F:→ bill0205: 2,1 则 4,2这笔会找不到 03/28 11:11
4F:→ cutekid: 如果 UID ↔marID 有 order(降幂、升幂)关系的话,就有解 03/28 13:03
5F:→ cutekid: 如果没有,例如: 03/28 13:03
6F:→ cutekid: 2,null 03/28 13:04
7F:→ cutekid: 1,2 03/28 13:04
8F:→ cutekid: 3,1 03/28 13:11
9F:→ cutekid: 4,3 03/28 13:11
10F:→ cutekid: 假设 UID 从 2 开始,就无法用这篇的方法解了 03/28 13:11
※ 编辑: cutekid (1.168.27.75), 03/28/2018 13:12:12
11F:推 bill0205: 感谢 ^^ 03/28 15:26