sql查询,以查找列表顶部的“希望顺序完全匹配”

sql查询,以查找列表顶部的“希望顺序完全匹配”,sql,oracle,Sql,Oracle,要在列表中首先显示精确匹配项的sql查询: 数据集:abcd、a、b、bc、bcd select * from table where data like "%bc%"; 它应该按bc、abcd、bcd的顺序显示。我认为您可以使用这样一个查询来返回预期结果 select * from table where data='bc' union all select * from table where data like '%bc%' and data<>'bc'

要在列表中首先显示精确匹配项的sql查询: 数据集:abcd、a、b、bc、bcd

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

它应该按bc、abcd、bcd的顺序显示。

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

select * from table where data='bc'
union all
select * from table where data like '%bc%' and data<>'bc' 
正如你所说的-按匹配排序

一种方法是:

select *
from t
where data like '%bc%'
order by (case when data = 'bc' then 1 else 2 end);
或者,如果您不想键入太多内容:

order by nullif(data, 'bc') desc
降序排序将空值放在第一位。

许多方法之一:

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)

.

为什么bcd是最后一个?没关系,只需给出prefer to exact match@juergendwithout order by没有在任何orderunion中显示的保证所有都不保证按特定顺序返回结果。我编辑了我的答案,如果我们在第二个select命令末尾添加一个order by,它将返回问题中提到的确切结果。大量的过度杀戮。Gordon Linoff和Andrei Ogedov展示了更有效的方法来解决这个问题。
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)