在本教程中将学习如何使用oracle where
子句来指定过滤的条件返回符合查询条件的行记录。
where
子句指定select
语句返回符合搜索条件的行记录。下面说明了where
子句的语法:
select
column_1,
column_2,
...
from
table_name
where
search_condition
order by
column_1,
column_2;
where
子句出现在from
子句之后但在order by子句之前。在where关键字之后是search_condition
- 它定义了返回行记录必须满足的条件。
除了select
语句之外,还可以使用delete或update语句中的where
子句来指定要更新或删除的行记录。
请参阅示例数据库中的以下产品(products
)表,其表结构如下 -
以下示例仅返回名称为“kingston”
的产品:
select
product_name,
description,
list_price,
category_id
from
products
where
product_name = 'kingston';
执行上面示例中的查询语句,得到以下结果 -
在这个例子中,oracle按以下顺序评估子句:from where
和select
from
子句指定查询数据的表。where
子句基于条件(例如product_name ='kingston'
过滤行记录)。select
子句选择了应该返回的列。除了等于(=
)运算符之外,oracle还提供了下表中所示的许多其他比较运算符:
编号 | 运算符 | 描述 |
---|---|---|
1 | = |
等于 |
2 | != ,<> |
不等于 |
3 | > |
大于 |
4 | < |
小于 |
5 | >= |
大于或等于 |
6 | <= |
小于或等于 |
7 | in | 等于值列表中的任何值 |
8 | any/some/all | 将值与列表或子查询进行比较。它必须以另一个运算符(例如:= ,> ,< )作为前缀。 |
9 | not in | 不等于值列表中的任何值 |
10 | [not] between n and m | 相当于[not] >= n 且 <= y 。 |
11 | [not] exists | 如果子查询返回至少一行,则返回true |
12 | is [not] null |
测试null 的值 |
例如,要获取标价大于500
的产品,请使用以下语句:
select
product_name,
list_price
from
products
where
list_price > 500;
执行上面查询语句,得到以下结果 -
例如,要获取属于类别编号是4
且标价大于500
的所有主板,请使用以下语句:
select
product_name,
list_price
from
products
where
list_price > 500
and category_id = 4;
执行上面示例代码,得到以下结果 -
要查找具有两个值之间的值的行,请在where
子句中使用between
运算符。
例如,要获取标价在650
到680
之间(650 <= list_price <= 680
)的产品,请使用以下语句:
select
product_name,
list_price
from
products
where
list_price between 650 and 680
order by
list_price;
执行上面查询语句,得到以下结果 -
请注意,以下表达式是等效的:
select
product_name,
list_price
from
products
where
list_price >= 650 and list_price <= 680
order by
list_price;
要查询值列表中的行记录,可以使用in运算符,如下所示:
select
product_name,
category_id
from
products
where
category_id in(1, 4)
order by
product_name;
执行上面查询语句,得到以下结果 -
表达方式:
category_id in (1, 4)
等效于 -
category_id = 1 or category_id = 4
以下语句检索名称以asus
开头的产品:
select
product_name,
list_price
from
products
where
product_name like 'asus%'
order by
list_price;
在这个例子中,我们使用like运算符来根据指定的模式来匹配行记录。
在本教程中,您已学习如何使用oracle where
子句为查询返回指定搜索条件的数据记录。