2014-09-26 66 views
1

我有一個要求允許按名稱搜索(開始)。 此搜索將返回以某些字母開頭的所有項目以及包含以這些字母開頭的子項目的所有父項目。搜索以返回子項目和父項目

示例數據附在我的嘗試中。有沒有更好的方法來做到這一點?非常感謝你提前。

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) 

回答

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

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)) 
+0

謝謝!這適用於我的樣本數據,但在我的真實生活處方藥表上運行很長時間。我將不得不以實際執行計劃運行,以查看是否缺少一些索引。 – Daisy 2014-09-26 23:37:41