sql查询列表顶部的like-to-order精确匹配

uqjltbpv  于 2021-07-29  发布在  Java
关注(0)|答案(4)|浏览(231)

sql查询,以便在列表中首先显示完全匹配的数据集:“d”、“a”、“b”、“bc”、“bcd”

select * from table where data like "%bc%";

它应该按bc,d,bcd的顺序显示。

kkbh8khc

kkbh8khc1#

多种方法之一:

with
  t as (
    select 'abcd' c from dual union all
    select 'a'    from dual union all
    select 'b'    from dual union all
    select 'bc'   from dual union all
    select 'bcd'  from dual
  )
select *
from t
where c like '%bc%'
order by length(c)

演示。

kgsdhlau

kgsdhlau2#

就像你说的-按匹配排序。

SQL> with test (col) as
  2    (select 'abcd' from dual union all
  3     select 'a'    from dual union all
  4     select 'b'    from dual union all
  5     select 'bc'   from dual union all
  6     select 'bcd'  from dual
  7    )
  8  select col
  9  from test
 10  where col like '%' || '&&par_search_string' ||'%'
 11  order by utl_match.jaro_winkler_similarity(col, '&&par_search_string') desc;
Enter value for par_search_string: bc

COL
----
bc
bcd
abcd

SQL> undefine par_search_string
SQL> /
Enter value for par_search_string: cd

COL
----
bcd
abcd

SQL>
zi8p0yeb

zi8p0yeb3#

一种方法是:

select *
from t
where data like '%bc%'
order by (case when data = 'bc' then 1 else 2 end);

或者如果你不想打那么多:

order by nullif(data, 'bc') desc

降序排序 NULL 价值观优先。

col17t5w

col17t5w4#

我认为您可以使用这样的查询来返回预期的结果。

select * from table where data='bc'
union all
select * from table where data like '%bc%' and data<>'bc'

相关问题