首先使用sql中的like query显示最大匹配

时间:2013-06-03 05:04:35

标签: c# asp.net sql oracle

我正在使用SQL查询,如下所示

string strPosition = "Blithe Spirit";
        string[] ArrPosition=new string[5];
        string strPositionList = "";
        if (!strPosition.Equals(""))
        {
            ArrPosition = strPosition.Split(' ');
        }
        foreach (string word in ArrPosition)
        {
            strPositionList += "CurrPosi like '%" + word + "%' or ";
        }

  string str="select * from Tbl_Book where Book_Name like %"+strPosition+"% or ("+strPositionList +")";

在上面的查询中。我得到的结果为Book Name,如Blithe Spirit,Blithe,Spirit。这是我需要的输出,但获取输出顺序为数据库行顺序。我需要最大匹配,即完全匹配' Blithe Spirit'作为第一个,剩下的'Blithe'和'Spirit'作为下一个匹配

4 个答案:

答案 0 :(得分:0)

尝试一次

string str="select * from Tbl_Book where Book_Name like '%"+strPosition+"%' or ("+strPositionList +")";

答案 1 :(得分:0)

我不能马上想到另一个解决方案,但你可以结合你的结果,但首先查询什么是几乎完全匹配,然后查询相似性并使用联合加入它们。 (我没有使用过oracle(你的一个标签)所以我不确定它的确切语法。)

select 1 as [i], * from Tbl_Book where Book_Name like '%"+strPosition+"%'
union
select 2 as [i], * from Tbl_Book where Book_Name not like '%"+strPosition+"%' and "+strPositionList

答案 2 :(得分:0)


 WITH CTE (COLUMN_NAMES)    /*Specify all column names(tbl_book) here*/
  AS
  (
  SELECT * from Tbl_Book where Book_Name like 'Blithe Spirit'
  ),
  CTE2
  AS
  (
  SELECT * from Tbl_Book where Book_Name like 'Blithe'
  ),
  CTE3
  AS
  (
  SELECT * from Tbl_Book where Book_Name like 'Spirit'
  )
  SELECT * FROM CTE
  UNION
  SELECT * FROM CTE2 
  UNION
  SELECT * FROM CTE3

答案 3 :(得分:0)

这应该是关闭的:

SELECT *
FROM (
  SELECT 1 as sortorder,*
  FROM tbl_book
  WHERE book_name like %"+strPosition+"%
  UNION
  SELECT 2 as sortorder,*
  FROM tbl_book
  WHERE book_name like ("+strPositionList +")
) t1
ORDER BY sortorder