SQLite复杂查询帮助

时间:2010-07-21 15:03:07

标签: database 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,那么如果它返回ItemID,它应该是FIRST ItemID而不是LAST ItemID

我有以下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

它返回数据......但按类别分组.CatTitle表示Content.ItemID将返回2,而不是1

任何想法?

1 个答案:

答案 0 :(得分:0)

假设您使用整数作为content.ItemID并且第一个结果以较低的ItemID为特征修改查询以包含min(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

应该做的工作。

相关问题