sql从一个表查询数据,插入到另一个表中 10

已知表a,如左表。需要实现下表编写sql语言为了得到下表b... 已知表a,如左表。需要实现下表
编写sql语言
为了得到下表b
展开
 我来答
百度网友cc7dce5
推荐于2017-12-15 · TA获得超过371个赞
知道小有建树答主
回答量:436
采纳率:0%
帮助的人:371万
展开全部
一级分类 ID select id from a where fatherid = 0

二 级分类 ID select id from a where fatherid in(select id from a where fatherid = 0)

下面的查询就是你要的最终结果

select t3.id as first_id,t3.name as first_name,t2.id as second_id,t2.id as second_name,t1.id as third_id,t1.name as third_name from a T1
left join a t2 on t2.id = t1.fatherid
left join a t3 on t3.id = t2.fatherid
where t1.id not in(select id from a where fatherid in(select id from a where fatherid = 0))

如果你有表 B
那么就是
insert into b values(f_id,f_name,s_id,s_name,t_id,t_name)
select t3.id as first_id,t3.name as first_name,t2.id as second_id,t2.id as second_name,t1.id as third_id,t1.name as third_name from a T1
left join a t2 on t2.id = t1.fatherid
left join a t3 on t3.id = t2.fatherid
where t1.id not in(select id from a where fatherid in(select id from a where fatherid = 0))

不过一般不建议你这么多
1, 这样做 下级分类就只能3级了
2,对表B的更新会比较频繁

建议你做一个表值函数 随时用 随时调就可以
百度网友c4bfb32
2015-01-08 · TA获得超过239个赞
知道答主
回答量:47
采纳率:0%
帮助的人:14.4万
展开全部
select * into 临时表_1级目录 from 表A where fatherid=0
select * into 临时表_2级目录 from 表A a inner join 临时表_1级目录 b on a.fatherid=b.id
select * into 临时表_3级目录 from 表A a inner join 临时表_2级目录 b on a.fatherid=b.id

select * from
(select id as first_id,name as first_name from 临时表_1级目录) a,
(select id as second_id,name as second_name from 临时表_2级目录) b,
(select id as third_id,name as third_name from 临时表_3级目录) c
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式