第7节.子查询
1.SQL Server子查询
子查询是嵌套在另一个语句(如:[select],[insert],[update]或[delete])中的查询。
以下语句显示如何在 select语句的[where]子句中使用子查询来查找位于纽约( New York )的客户的销 售订单:
select
order_id,
order_date,
customer_id
from
sales.orders
where
customer_id in (
select
customer_id
from
sales.customers
where
city = 'New York'
)
order by
order_date desc;
2.SQL Server嵌套子查询
子查询可以嵌套在另一个子查询中。
SQL Server最多支持 32 个嵌套级别。
请考虑以下示例:
select
product_name,
list_price
from
production.products
where
list_price > (
select
AVG (list_price)
from
production.products
where
brand_id in (
select
brand_id
from
production.brands
where
brand_name = '上海永久'
or brand_name = '凤凰'
)
)
order by
list_price;
首先,SQL Server执行以下子查询以获取品牌名称为 ‘上海永久’ 和 ‘凤凰’ 的品牌标识号列表:
select
brand_id
from
production.brands
where
brand_name = '上海永久'
or brand_name = '凤凰'
第二步,SQL Server计算属于这些品牌的所有产品的平均价格。
select
avg (list_price)
from
production.products
where
brand_id in (1,2)
第三步,SQL Server查找价格高于 ‘上海永久’ 和 ‘凤凰’ 品牌的所有产品的平均定价的产品。
select
*
from
production.products
where
list_price > (
select
avg(list_price)
from
production.products
where
brand_id IN (
select
brand_id
from
production.brands
where
brand_name in('上海永久', '凤凰')
)
)
1.SQL Server子查询
子查询是嵌套在另一个语句(如:[select],[insert],[update]或[delete])中的查询。
以下语句显示如何在 select语句的[where]子句中使用子查询来查找位于纽约( New York )的客户的销 售订单:
select
order_id,
order_date,
customer_id
from
sales.orders
where
customer_id in (
select
customer_id
from
sales.customers
where
city = 'New York'
)
order by
order_date desc;
2.SQL Server嵌套子查询
子查询可以嵌套在另一个子查询中。
SQL Server最多支持 32 个嵌套级别。
请考虑以下示例:
select
product_name,
list_price
from
production.products
where
list_price > (
select
AVG (list_price)
from
production.products
where
brand_id in (
select
brand_id
from
production.brands
where
brand_name = '上海永久'
or brand_name = '凤凰'
)
)
order by
list_price;
首先,SQL Server执行以下子查询以获取品牌名称为 ‘上海永久’ 和 ‘凤凰’ 的品牌标识号列表:
select
brand_id
from
production.brands
where
brand_name = '上海永久'
or brand_name = '凤凰'
第二步,SQL Server计算属于这些品牌的所有产品的平均价格。
select
avg (list_price)
from
production.products
where
brand_id in (1,2)
第三步,SQL Server查找价格高于 ‘上海永久’ 和 ‘凤凰’ 品牌的所有产品的平均定价的产品。
select
*
from
production.products
where
list_price > (
select
avg(list_price)
from
production.products
where
brand_id IN (
select
brand_id
from
production.brands
where
brand_name in('上海永久', '凤凰')
)
)