Foxpro数据库
有下表:Table
名称    下位词
世界    欧洲
世界    亚洲
世界    美洲
………………
美洲    北美洲
美洲    南美洲
北美洲  加拿大
北美洲  美国
南美洲  巴西
南美洲  智利
欧洲    德国
欧洲    英国
…………………
我想写这样一条SQL语句:
输入一个词,把它的所有下为词查询出来
比如我输入“美洲”,应该返回的查询结果是:
美洲、北美洲、南美洲、加拿大、美国、智利、巴西
我知道这叫单表连接查询,但是我只会写一层的:
Select Table1.名称 From Table Table1, Table Table2
Where Table1.名称=‘美洲’And Table1.下为词=Table2.名称
这样只能查出来:北美洲、南美洲。剩下的查不出来了。
请高手们帮帮忙!!!

解决方案 »

  1.   

    select * from table where 名称 like '%美洲%' or 下位词 like '%美洲%'
      

  2.   

    select distinct l.名称 from table1 l
    left join table1 r on l.下位词=r.名称
    union
    select distinct l.下位词 from table1 l
    left join table1 r on l.下位词=r.名称
    where l.下位词 is not null
    union
    select distinct r.下位词 from table1 l
    left join table1 r on l.下位词=r.名称
    where r.下位词 is not null
      

  3.   

    select * from table where 名称 like '%美洲%' 
    就这个就可以得出你要的结果了
      

  4.   

    楼上的你可真会开玩笑
    还有这样写的那位大哥:select * from table where 名称 like '%美洲%' or 下位词 like '%美洲%' 你这样也是不对的啊!!
    说用视图的那位兄弟,能具体说说想法吗??我觉得CSDN里真的没什么高人……(看到了回答我心寒)
      

  5.   

    我昨天也遇到类似的问题,经高手指点,解决了,请参考下面:
    create table tb(ID int,PID int,Name nvarchar(50))
    ID          PID         Name                                               
    ----------- ----------- -------
    1           0           中國
    2           1           廣東省
    3           1           湖南省
    4           2           廣州市
    5           2           佛山市
    declare @ID int 
    set @ID=2                --在這裡設置iddeclare @t table (Parent int,Child int,Level int)
    declare @l int
    set @l=0insert into @t
          select PID,ID,@l from tb where ID=@IDwhile @@rowcount>0
         begin 
             set @l=@l+1          insert into @t
                select  b.Child,a.ID,@l
                    from tb as a,@t as b
                         where a.PID=b.Child and b.Level=@l-1
         endselect b.*
        from @t as a 
           inner join tb as b on a.Child=b.ID結果;
    ID          PID         Name                                               
    ----------- ----------- -----------
    2           1           廣東省
    4           2           廣州市
    5           2           佛山市(3 row(s) affected)