2010-07-21 84 views
0

我有一個非常複雜的查詢在SQLite中進行,我需要一些幫助來理解如何去做。SQLite複雜查詢幫助

下面的例子是我的數據庫:

Category: 

CatID | CatTitle 
---------------- 
    1 | XYZ 
    2 | Sample 


Content: 

ItemID | ItemCatID | ItemText | ItemText2 | ItemText3 | ItemText4 
----------------------------------------------------------------- 
    1 |  1  | Test | Bla | Sample | MoreContent 
    2 |  1  | Test2 | BlaBla | Sample2 | Other Content 
    3 |  2  | Test3 | BlaBla2 | Sample3 | Other Content2 

現在,我基本上想要做一個查詢,在搜索字符串。(即「%XYZ%」與通配符),我想我不想搜索CatTitle,但也ItemText,ItemText2和ItemText3

我想返回的參數是:CatID,CatTitle,ItemID,如果可能的話,「ItemFilteredText」(可以是任何從ItemText到ItemText4,取決於其中是匹配)

繼承人首先,如果這個查詢匹配CatTitle,那麼如果返回項ID,它應該是第一個項目ID和不是最後一個項目ID

我有以下SQL有些工作......

select DISTINCT Category.CatID, 
     Category.CatTitle, 
     Content.ItemID, 
     Content.ItemText, 
     Content.ItemText2, 
     Content.ItemText3 
from Content,Category 
where Category.CatID = Content.ItemCatID 
     AND (Category.CatTitle like'%XYZ%' 
      OR Content.ItemText like '%XYZ%' 
      OR Content.ItemText2 like '%XYZ%' 
      OR Content.ItemText3 like '%XYZ%') 
GROUP BY Category.CatTitle ORDER BY Category.CatID ASC 

它返回數據...但通過Category.CatTitle分組意味着Content.ItemID將返回2,而不是1

任何想法?

回答

0

假設你使用整數爲content.ItemID和第一結果的特徵在於較低的ItemID修改查詢以包括分鐘(Content.ItemID)

select DISTINCT Category.CatID, Category.CatTitle, min(Content.ItemID), Content.ItemText, Content.ItemText2, Content.ItemText3 from Content,Category where Category.CatID = Content.ItemCatID AND (Category.CatTitle like'%XYZ%' OR Content.ItemText like '%XYZ%' OR Content.ItemText2 like '%XYZ%' OR Content.ItemText3 like '%XYZ%') GROUP BY Category.CatTitle ORDER BY Category.CatID ASC 

應做的工作。

+0

謝謝,那是做的工作。 我想接下來的問題是如何將ItemText的值返回給單個別名下的ItemText3,如果它們匹配...(即ItemFilteredText)... 除此之外...如果CatTitle匹配,則只返回CatID& CatTitle(所有其他值應爲空),否則如果從ItemText到ItemText3的任何項匹配,則返回該值作爲別名(但不返回同一行的多個結果 所以它應該顯示: – AAA 2010-07-22 11:41:48