2009-05-29 88 views
0

我需要幫助設計一個用於返回網站搜索結果的查詢。用戶通過從屬性列表中選擇項目進行搜索。返回的每個搜索結果項必須具有用戶選擇的所有屬性。用於檢索搜索結果的SQL查詢

挑戰(對我來說至少是!)是搞清楚如何只返回具有所有屬性的結果而不是其中的任何一個。

搜索結果項(我們稱之爲WIDGET)位於WIDGET表中。可能的小部件屬性位於ATTRIBUTE表中。聯結表(WIDGETATTRIBUTEJUNCTION)存儲每個WIDGET的0,1..n個實際屬性。

我找不到一個查詢,當提供一個控件屬性列表時,它將返回具有這些屬性中每一個屬性的行。我懷疑我可能會使用ALL子查詢和/或INTERSECT,但不知道如何。

回答

1

您可以使用類似於下面的東西,

SELECT WidgetID FROM Widget INNER JOIN WidgetAttributes WA ON WA.Key = SearchAttributes.Key AND WA.WidgetID = Widget.WidgetID GROUP BY WidgetID HAVING COUNT(Widget.WidgetID) > @SearchAttributesCount 

的關鍵是在GROUP BY具有其限制爲只納入符合所有的屬性,所有的Widget行語句。

0

如果只有SQL支持的陣列...

有幾個方法,你可以去這個問題,我的首選方法是發送一個字符串(包含屬性ID)到SQL那麼字符串分割成表。

喜歡的東西:

create function dbo.fn_makeArray (@value nvarchar(max)) 
    returns @table table([key] nvarchar(256)) 
    begin 
     declare @start int; 
     declare @end int; 

     select @start = 1, @end = charindex(',', @value); 

     while (@start < len(@value) + 1) 
     begin 
      if (@end = 0) 
       set @end = len(@value) + 1; 

      insert into @table ([key]) 
      values(substring(@value, @start, @end - @start)); 

      set @start = @end + 1; 
      set @end = charindex(',', @value, @start); 
     end 
     return; 
    end 
0

我們有這樣的一段時間後一個問題:

select WidgetName,AttributeName 
from Widgets 
left join WALinks on WALinks.wid = WidgetID 
left join Attributes on WALinks.aid = AttributeID 

where WidgetID in 
(
    select wId 
    from waLinks 
    where aid in (1,3) 
    group by wId 
    having count(aId) = 2 
) 

然後,您可以設置「在(1,3)」,始終在屬性列表將計數查詢的數量調整爲您匹配的屬性的數量。