实现类似于baidu的那种用空格键的分词查询

【全文】
 ///
  /// 实现类似于baidu的那种用空格键的分词查询
  ///
  /// 要查询表的字段集合
  /// 要查询的表名
  /// 查询的关键字
  /// 查询的模式
  /// 具体的查询语句
  private string GetSearchWord(string[] tableField ,string tableName ,string strKeyword ,string strSearchMode)
  {
   StringBuilder strCondition = new StringBuilder();
   string [] KeywordArray;
   string strTemp = "";
            strCondition.Append("SELECT ");
   string strWhere ="";
   // 获得要查询表的字段名称
   foreach(string sqlField in tableField)
   {
    strWhere += sqlField + "," ;
   }
   strWhere = strWhere.TrimEnd(new char[]{','});
   strCondition.Append(strWhere + " FROM "+tableName+" WHERE ");
   
   if(strKeyword.IndexOf(',')!=-1)
    KeywordArray=strKeyword.Split(',');
   else
    if(strKeyword.IndexOf('|')!=-1)
    KeywordArray=strKeyword.Split('|');
   else
    KeywordArray=strKeyword.Split(null);
   // 完全匹配模式
   if(strSearchMode == "1")
   {
     strWhere="";
    foreach(string sqlField in tableField)
    {
      strWhere += sqlField + "+";
    }
    strWhere=strWhere.TrimEnd(new char[] {'+'});
    strTemp += strWhere + " like '%"+strKeyword+"%'";
   }
   else
   {
    // 部分匹配模式
    if(strSearchMode=="2")
    {
     strWhere = "";
     foreach(string sqlField in tableField)
     {
      strWhere += sqlField + "+";
     }
     strWhere=strWhere.TrimEnd(new char[] {'+'});
     strTemp += strWhere + " like '";
     strWhere="";
     for (int i=0;i     {
      strWhere+="%"+KeywordArray[i];
     }
     strTemp+=strWhere +"%'";
    }
    // 单词匹配模式
    if(strSearchMode=="3")
    {
     strWhere="";
     foreach(string sqlField in tableField)
     {
      strWhere +=" "+ sqlField + "+";
     }
     strWhere=strWhere.TrimEnd(new char[] {'+'});
  
     string strSqlKeyword="";
     for (int i=0;i     {
      strSqlKeyword+=strWhere+" like" +" '%"+KeywordArray[i]+"%' or";
     }
     strSqlKeyword=strSqlKeyword.TrimEnd(new char[] {'o','r'});
     strTemp +=strSqlKeyword;
    } 
   }
   return strCondition.Append(strTemp).ToString();

  }

posted on 2007-06-09 10:01  噢耶游戏  阅读(708)  评论(1编辑  收藏  举报