子查询
子查询(Subquery)是指出现在其他SQL语句内的LELECT子句。
例如:
SELECT * FROM t1 WHERE col1 = (SELECT col2 FROM t2);
其中SELECT * FROM t1,称为Outer Query/Outer Statement
SELECT * FROM t2,称为SubQuery。
- 子查询指嵌套在查询内部,且必须始终出现在圆括号内。
- 子查询可以包含多个关键字或条件,
如DISTINCT、GROUP BY、ORDER BY、LIMIT,函数等。 - 子查询的外层查询可以是:SELECT,INSERT,UPDATE,SET或DO。
- 子查询可以返回标量、一行、一列或子查询
使用比较运算符的子查询
运算符:
=、>、<、>=、<=、<>、!=、<=>
语法结构:
operand comparison_operator subquery
demo:
查询goods_price平均值,并且使用ROUND,四舍五入,保留两位小数
SELECT ROUND(AVG(goods_price),2) FROM tdb_goods;
利用上句,用子查询方法写出大于平均数的物品信息。
SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price>(SELECT ROUND(AVG(goods_price),2) FROM tdb_goods);
如图:
用ANY、SOME或ALL修饰的比较运算符
demo:
查询goods_cate=’超级本’的goods_price
SELECT goods_price FROM tdb_goods WHERE goods_cate=’超级本’;
利用上句,用子查询加上ANY查询出,比上句的goods_price的其中一个(4299.000)大的货物信息
SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price>ANY (SELECT goods_price FROM tdb_goods WHERE goods_cate=’超级本’);
使用[NOT] IN的子查询
语法结构:
operand comparison_Ooperator [NOT] IN (subquery)
- =ANY运算符与IN等效
- !=ALL或<>ALL运算符与NOT IN 等效
demo:
NOT IN:
SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price NOT IN (SELECT goods_price FROM tdb_goods WHERE goods_cate=’超级本’);
!=ALL:
SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price !=ALL (SELECT goods_price FROM tdb_goods WHERE goods_cate=’超级本’);
两者返回的结果一致:
使用[NOT] EXISTS的子查询
如果子查询返回任何行,EXISTS将返回TRUE;否则为FALSE。
demo:
如果表tdb_goods不为空,那么把goods_id,goods_name全部查出来
SELECT goods_id AS ID,goods_name AS CATE FROM tdb_goods WHERE EXISTS (SELECT * FROM tdb_goods);