SQL高手!给我解决难题!

dingzh 2000-09-07 05:36:00
你好!
我有这么一个数据库简单描述如下:
field1 field2
---------------
a b
a c 用sql语句要求找出所有与a相关的记录,也就是左边前7个
a d 记录。多谢了!
b e
b f
e g
g i
aa c
c cc
...全文
168 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
hsh 2000-09-13
  • 打赏
  • 举报
回复
假设你的表叫yourtalbe, 字段类型为Varchar(10)
--
begin
--
create table #t1(Field varchar(10))
--
declare @C1 int
--
insert into #t select field1 from yourtalbe where field1='a' group by field1
--
select @c1=@@rowcount
--
while @C1>0
begin
--
insert into #t1
select field2 from yourtalbe a, #t1 b where a.field1=b.field group by field2
--
select @c1=@@rowcount
--
end
--
select field into #t2 from #t1 group by field
--
select a.* from yourtalbe a, #t2 b where a.field1=b.field
--
end
--
return

pjy 2000-09-13
  • 打赏
  • 举报
回复
建一个临时表。然后遍历!
lynx 2000-09-09
  • 打赏
  • 举报
回复
如果只存在两层关系的数据的话,可以用以下语句,urtable是表名;
select * from urtable where (field1 in (select field2 from urtable where field1='a')) or field1='a';
如果存在与a的关联关系达到两层以上的数据的话,我看你还是使用树的遍历吧.
qiuzhi 2000-09-08
  • 打赏
  • 举报
回复
假设你的表叫yourtalbe, 字段类型为Varchar(10)
下面是我的想到的,希望大虾们多多指教

create table #t1(Field varchar(10))
create table #t2(Field varchar(10))
declare @C1 int,@C2 int
select @C1=0
select @C2=1
while @C2>@C1
begin
select @C1=@C2
delete from #T2
insert into #T2(Field)
select distinct(Field2)
from yourtable, #T1
where yourtable.Field1=#T1.Field or yourtable.Field1='a'
delete from #T1

insert into #T1(Field)
select Field from #T2
select @C2=count(*) from #T2
end

select y.* from yourtable y ,#T1 where y.field1=#T1.Field

wwwunix 2000-09-07
  • 打赏
  • 举报
回复
要写一个存储过程,算法可用树的遍历.

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧