带有文本值的Oracle BETWEEN运算符

时间:2017-02-27 03:35:14

标签: sql oracle

查询1:

SELECT cust_last_name, cust_credit_limit
FROM customers
WHERE (UPPER(cust_last_name) LIKE 'A%' OR
       UPPER(cust_last_name) LIKE 'B%' OR
       UPPER(cust_last_name) LIKE 'C%' AND cust_credit_limit < 10000;

查询2:

SELECT cust_last_name,cust_credit_limit
FROM customers
WHERE UPPER(cust_last_name) BETWEEN 'A' AND 'C' AND
cust_credit_limit < 10000;

我正在尝试生成姓氏和信用额度的报告,这些客户的姓氏以A,B或C开头且信用额度低于10000。 哪种方法正确?

2 个答案:

答案 0 :(得分:2)

您无法在A和C之间直接使用,因为不会包含以C开头的值,如CDE。因为你需要从A开始的所有行开始 使用C,您可以使用自定义范围:

select cust_last_name, cust_credit_limit
from customers
where UPPER(cust_last_name) >= 'A'
  and UPPER(cust_last_name) < 'D'
  and cust_credit_limit < 10000

它找到A(包括)和D(不包括)之间的所有字符串。

Demo

或使用subs substr:

select cust_last_name, cust_credit_limit
from customers
where UPPER(substr(cust_last_name,1,1)) between 'A' and 'C'
    and cust_credit_limit < 10000

Demo

答案 1 :(得分:0)

Oracle可能会使用以下查询的索引:

select cust_last_name, cust_credit_limit
from customers
where ((cust_last_name >= 'A' and cust_last_name < 'D') or
       (cust_last_name >= 'a' and cust_last_name < 'd')
      ) and
      cust_credit_limit < 10000;

为了提高性能,我建议您使用upper()版本并在customers(upper(cust_last_name), cust_credit_limit)上创建索引。