where是oracle中的条件查询子句,本教程,将学习如何使用oracle where子句来指定过滤的条件返回符合查询条件的行记录。
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子句来指定要更新或删除的行记录。
oracle where示例
参阅示例数据库中的以下产品(products)表,其表结构如下:
1. 通过使用简单的相等运算符来查询行记录
以下示例仅返回名称为“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子句选择了应该返回的列。
2. 使用比较运算符选择行记录
除了等于(=)运算符之外,oracle还提供了下表中所示的许多其他比较运算符:
编号 | 运算符 | 描述 |
---|---|---|
1 | = | 等于 |
2 | != ,<> | 不等于 |
3 | > | 大于 |
4 | < | 小于 |
5 | >= | 大于等于 |
6 | <= | 小于等于 |
7 | in | 等于值列表中的任何值 |
8 | any/some/all | 将值与列表或子查询进行比较。它必须以另一个运算符(例如:= ,> ,< )作为前缀。 |
9 | not in | 不等于值列表中的任何值 |
10 | [not] between n and m | 相当于[not] >= n 且 <= m 。 |
11 | [not] exists | 如果子查询返回至少一行,则返回true |
12 | is [not] null | 测试null 的值 |
例如,要获取标价大于500的产品,请使用以下语句:
select product_name, list_price from products where list_price > 500;
执行上面查询语句,得到以下结果:
3. 选择符合某些条件的行
要组合条件,可以使用and,or和not逻辑运算符。
例如,要获取属于类别编号是4且标价大于500的所有主板,请使用以下语句:
select product_name, list_price from products where list_price > 500 and category_id = 4;
执行上面示例代码,得到以下结果:
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;
5. 选择符合值列表中的行记录
要查询值列表中的行记录,可以使用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
6. 选择包含值的行作为字符串的一部分
以下语句检索名称以asus开头的产品:
select product_name, list_price from products where product_name like 'asus%' order by list_price;
在这个例子中,我们使用like运算符来根据指定的模式来匹配行记录。