搜索以返回子项和父项

时间:2014-09-26 01:27:34

标签: sql sql-server-2012

我要求允许按名称搜索(以...开头)。 此搜索将返回以某些字母开头的所有项目以及包含以这些字母开头的子项目的所有父项。

我试图做的附加示例数据。有没有更好的方法呢?非常感谢你提前。

declare @A table ( ID int ,
                Name varchar(100),
                ParentID int)
INSERT INTO @A Values ( 1, 'Apples', 10)
INSERT INTO @A Values ( 2, 'Bananas', 20)
INSERT INTO @A Values ( 3, 'Mangos ', 30)
INSERT INTO @A Values ( 4, 'Avocados ', 10)
INSERT INTO @A Values ( 5, 'Blueberries ', 20)
INSERT INTO @A Values ( 6, 'Blackberries ', 20)
INSERT INTO @A Values ( 7, 'Apricots ', 10)
INSERT INTO @A Values ( 10, 'Fruits beginning with A ', 0)
INSERT INTO @A Values ( 20, 'Fruits beginning with B ', 0)
INSERT INTO @A Values ( 30, 'Fruits beginning with C ', 0)
-- when searching for A should find Apples, Avocados, Apricots 
-- and 'Fruits beginning with A' (ie their parent).
DECLARE @Letter varchar (10) = 'A%'

select id, name, ParentID from @a 
where name like @Letter 
UNION
select id, name,parentID from @a
where ID  in (select distinct ParentID from @a 
where name like @Letter )

2 个答案:

答案 0 :(得分:0)

使用OR运算符:

select id, name,parentID 
from @a
where name like @Letter or
    ID  in (select ParentID from @a 
        where name like @Letter)

enter image description here

答案 1 :(得分:0)

这是使用EXISTS的一个选项,它具有良好的执行计划:

select id, name,parentID 
from a
where exists (select 1
              from a a2
              where name like @Letter and (a.id = a2.id or a.id=a2.parentid))