Oracle更优先考虑%term而不是%term%

时间:2013-10-21 06:35:22

标签: sql oracle

我有一个类似这样的查询

select city_desc from mst_city where upper(city_desc) like upper('%branch%')

它会填充结果those which start with branchthose which contains branch。以随机顺序。

我想对其进行排序,以便结果首先显示those which start with branch的所有搜索结果,然后显示those which contains branch的所有搜索结果。

我该怎么做?我知道我可能不得不使用Order By条款。但我无法弄清楚

2 个答案:

答案 0 :(得分:6)

尝试以下解决方案:

WITH mst_city AS
  (SELECT 'branch test' AS city_desc FROM dual
   UNION ALL SELECT 'test branch test' FROM dual
   UNION ALL SELECT 'a branch' FROM dual
   UNION ALL SELECT 'branch' FROM dual
   UNION ALL SELECT 'something different' FROM dual)
SELECT
    city_desc
  FROM (
    SELECT
        city_desc,
        CASE
          WHEN UPPER(city_desc) LIKE 'BRANCH%' THEN 1
          ELSE 2
        END AS match_order
      FROM mst_city
    WHERE
      UPPER(city_desc) LIKE '%BRANCH%'
    )  
ORDER BY match_order;

答案 1 :(得分:4)

您只需要一个条件为'BRANCH%'的排序顺序:

select city_desc from mst_city where upper(city_desc) like '%BRANCH%'
order by case when upper(city_desc) like 'BRANCH%' then 1 else 2 end