首先在sql中使用like查询显示最大匹配

本文关键字:显示 查询 like sql | 更新日期: 2023-09-27 18:16:36

我使用如下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 +")";

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

首先在sql中使用like查询显示最大匹配

我不能马上想到另一个解决方案,但你可以联合你的结果,但首先查询什么是几乎完全匹配,然后查询相似度,并使用联合连接它们。(我没有使用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

试一下

string str="select * from Tbl_Book where Book_Name like '%"+strPosition+"%' or ("+strPositionList +")";
WITH CTE (COLUMN_NAMES)/*指定这里所有的列名称(tbl_book) */作为(SELECT * from Tbl_Book where Book_Name like 'Blithe Spirit'),CTE2作为(SELECT * from Tbl_Book where Book_Name like 'Blithe'),CTE3作为(SELECT * from Tbl_Book where Book_Name like 'Spirit')从cte中选择*联盟从cte2中选择*联盟从cte3中选择*

应该接近:

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