sql子查询表达式基础
子查询是一个嵌套在 SELECT、INSERT、UPDATE 或 DELETE 语句或其他子查询中的查询。任何允许使用表达式的地方都可以使用子查询。在以下示例中,子查询在 SELECT 语句中被用作名为 MaxUnitPrice 的列表达式。
首先我们看几个例子
1。select ... where 列或运算式 比较运算运算【any|all](子查询)
只要主查询中列或运算式与子查询所得结果中任一(any)或全部(all)数据符合比较条件的话则主查询的结果为我们要的数据
选出不同的人金额最高的订单
select * from sales a
where tomat=(select max(totmat) from sales where name=a.name)
select sale_id,tot_amt
from sales
where tot_amt>any(select tot_amt from sales where sale_id='e0013'and 'order_date='1996/11/10')
2。select ...where 列或运算式[not] in (子查询)
只要主查询中列或运算式是在(不在)子查询所得结果列表中的话,则主查询的结果为我们要的数据
select sales_id,tot_amt
from sales
where sale _id in(select sale_id from employee where sex='F')
3.select ...where [not] exists ( 子查询)
子查询的结果至少存在一条数据时,则主查询的结果为我们要的数据。(exists)或自查询的结果找不到数据时,则主查询的结果为我们要的数据(not exists)
我们经常查询的两个表有多少重复的记录就用这个
以下范例让你找出滞销的产品,也就是尚未有任何销售记录的库存产品。此范例主要是查询以库文件中的每一条产品代码到销售明细表中去查询,如果查询不到任何一条,表示该产品未曾卖出任何一件。
select * from stock a
where not exists(select * from sale_item b
where a.prod_id=b.prod_id and a.stup_id=b.stup_id)
select emp_no,emp_name from employee
from employee a
where (select sum(tot_amt) from sales b where a.sale_id=b.emp_no)<200000
/www.aspxuexi.com/
然后我们摘选一段microsoft的帮助文章
子查询也称为内部查询或内部选择,而包含子查询的语句也称为外部查询或外部选择。
许多包含子查询的 Transact-SQL 语句都可以改用联接表示。其他问题只能通过子查询提出。在 Transact-SQL 中,包含子查询的语句和语义上等效的不包含子查询的语句在性能上通常没有差别。但是,在一些必须检查存在性的情况中,使用联接会产生更好的性能。否则,为确保消除重复值,必须为外部查询的每个结果都处理嵌套查询。所以在这些情况下,联接方式会产生更好的效果。以下示例显示了返回相同结果集的 SELECT 子查询和 SELECT 联接:
/* SELECT statement built using a subquery. */
SELECT Name
FROM AdventureWorks.Production.Product
WHERE ListPrice =
(SELECT ListPrice
FROM AdventureWorks.Production.Product
WHERE Name = 'Chainring Bolts' )
/* SELECT statement built using a join that returns
the same result set. */
SELECT Prd1. Name
FROM AdventureWorks.Production.Product AS Prd1
JOIN AdventureWorks.Production.Product AS Prd2
ON (Prd1.ListPrice = Prd2.ListPrice)
WHERE Prd2. Name = 'Chainring Bolts'
嵌套在外部 SELECT 语句中的子查询包括以下组件:
- 包含常规选择列表组件的常规 SELECT 查询。
- 包含一个或多个表或视图名称的常规 FROM 子句。
- 可选的 WHERE 子句。
- 可选的 GROUP BY 子句。
- 可选的 HAVING 子句。
本文主题子查询