在本教程中,您将学习如何使用oracle all
运算符将值与列表或子查询进行比较。
oracle all
操作符用于将值与子查询返回的值列表或结果集进行比较。
以下显示了与列表或子查询一起使用的all
运算符的语法:
operator all ( v1, v2, v3)
operator all ( subquery)
在这个语法中,
=
,!=
,>
,>=
,<
,<=
,后跟一个列表或子查询。使用all
运算符将值与列表进行比较时,oracle将初始条件扩展到列表的所有元素,并使用and
运算符将它们组合在一起,如下所示:
select
*
from
table_name
where
c > all (
v1,
v2,
v3
);
-- 以上语句转换为 all 运算符后
select
*
from
table_name
where
c > v1
and c > v2
and c > v3;
如果使用all
运算符将值与子查询返回的结果集进行比较,则oracle执行两步转换,如下所示:
select product_name,
list_price
from products
where list_price > all
( select list_price
from products
where category_id = 1 )
order by product_name;
-- 1st step: transformation that uses any
select product_name,
list_price
from products p1
where not( p1.list_price <= any
(select list_price
from products p2
where category_id = 1 ))
order by product_name;
-- 2nd step: transformation that eliminates any
select product_name,
list_price
from products p1
where not exists
(select p2.list_price
from products p2
where p2.category_id = 1
and p2.list_price >= p1.list_price )
order by product_name;
如果子查询不返回行,则以下条件的计算结果为true
:
operator all (subquery)
这意味着在where子句中使用上述条件的查询将返回所有行,以防子查询返回任何行。
select
*
from
table_name
where
col operator all(subquery);
以下示例查找每个类别中产品的平均标价:
select
round( avg( list_price ),2 ) avg_list_price
from
products
group by
category_id
order by
avg_list_price desc;
执行上面示例代码,得到以下结果 -
如果col
大于列表中的最大值,则表达式的计算结果为true
。
例如,以下查询查找标价大于平均价格列表最大价格的产品:
select
product_name,
list_price
from
products
where
list_price > all(
select
avg( list_price )
from
products
group by
category_id
)
order by
list_price asc;
执行上面示例代码,得到以下结果 -
如果col
小于列表中的最小值,则表达式的计算结果为true
。
select
product_name,
list_price
from
products
where
list_price < all(
select
avg( list_price )
from
products
group by
category_id
)
order by
list_price desc;
例如,以下查询将查找标价低于平均价格列表中最小价格的产品:
如果col
大于或等于列表中的最大值,则表达式的计算结果为true
。
以下语句返回列表价格大于或等于2200
的cpu产品:
select
product_name,
list_price
from
products
where
list_price >= all(
1000,
1500,
2200
)
and category_id = 1
order by
list_price desc;
执行上面示例代码,得到以下结果 -
如果col
小于或等于列表中的最小值,则表达式的计算结果为true
。
以下语句返回标价小于或等于列表中最小值的977.99
的cpu产品。
select
product_name,
list_price
from
products
where
list_price <= all(
977.99,
1000,
2200
)
and category_id = 1
order by
list_price desc;
执行上面示例代码,得到以下结果 -
如果col
匹配列表中的所有值,则表达式的计算结果为true
。
如果col
不匹配列表中的任何值,则表达式的计算结果为true
。
在本教程中,您已经学习如何使用oracle all
操作符将值与列表或子查询进行比较。